[英]connection persistence using httpclient
我使用httpclient.execute(請求)對同一個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());
}
為了在你的代碼中使用單個客戶端(基於Exception使用HttpRequest.execute():無效使用SingleClientConnManager:仍然分配連接和Lars Vogel Apache HttpClient - 教程 ):
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();
}
試試下面。
HttpUriRequest httpGet = new HttpGet(uri);
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.