使用httpclient连接持久性

时间:2013-02-27 06:33:51

标签: java performance persistence httpclient apache-httpclient-4.x

我使用httpclient.execute(request)对同一个url执行多个请求。 我可以为连续请求重新使用连接吗? 如何在不重复声明HttpClient的情况下优化代码。

for(int i=0;i<=50;i++)
{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("my_url");
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine().getStatusCode());
}

2 个答案:

答案 0 :(得分:8)

为了在您的代码中使用单个客户端(基于Exception using HttpRequest.execute(): Invalid use of SingleClientConnManager: connection still allocated和Lars Vogel Apache HttpClient - Tutorial):

  • 步骤1.将客户端生成移到for-loop
  • 之外
  • 步骤2.您应该阅读响应内容并关闭流。如果您不这样做,您将收到以下异常

    Exception in thread "main" java.lang.IllegalStateException: 
        Invalid use of SingleClientConnManager: connection still allocated.
    

在代码中:

//step 1
HttpClient client = new DefaultHttpClient();
for(int i=0;i<=50;i++) {
    HttpGet request = new HttpGet("my_url");
    HttpResponse response = client.execute(request);
    System.out.println(response.getStatusLine().getStatusCode());
    //step 2
    BufferedReader br = new BufferedReader(
        new InputStreamReader(response.getEntity().getContent()));
    //since you won't use the response content, just close the stream
    br.close();
}

答案 1 :(得分:0)

尝试以下。

HttpUriRequest httpGet = new HttpGet(uri);
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
相关问题