3

我使用httpclient.execute(请求)对同一个网址执行多个请求。 我可以为连续请求重新使用连接吗? 我该如何优化代码而无需一次又一次声明HttpClient。使用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()); 
} 
+1

是的,我试图寻找了很多。但我无法找到示例代码 – muchumanoj 2013-02-27 06:35:40

+0

是的,我尝试了很多和很多的变化,但我无法。如果你觉得开发人员很难找,那么请帮助我。我把客户端放在外面,然后尝试,它给出了错误:连接仍然打开。我该如何使用它。这将是我第一次尝试。 – muchumanoj 2013-02-27 06:40:41

回答

8

为了在代码中使用单个客户(基于Exception using HttpRequest.execute(): Invalid use of SingleClientConnManager: connection still allocated和Lars沃格尔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(); 
} 
+0

哇。有效。我刚刚关闭了流,它工作。我以为我从来没有打开过这个流,我只是在阅读状态码,并且不需要打开回应并关闭它。反正非常感谢:) :) – muchumanoj 2013-02-27 07:10:07

+0

@ user2071013不客气,永不放弃! :) – 2013-02-27 07:10:35

+0

我得到的错误:org.apache.http.client.protocol.ResponseProcessCookies processCookies。你能帮我解决这个问题吗? – muchumanoj 2013-02-27 07:10:56

0

请尝试以下。

HttpUriRequest httpGet = new HttpGet(uri); 
DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); 
HttpResponse httpResponse = defaultHttpClient.execute(httpGet); 
+0

我仍然得到:异常使用HttpRequest.execute():无效的SingleClientConnManager使用:连接仍然分配 – muchumanoj 2013-02-27 07:08:08

+2

尽管此代码片段可能会解决问题,[包括解释](http://meta.stackexchange.com/questions/114762 /解释完全基于代码的答案)确实有助于提高帖子的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。 – msrd0 2015-03-10 16:00:06