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