我使用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());
}
答案 0 :(得分:8)
为了在您的代码中使用单个客户端(基于Exception using HttpRequest.execute(): Invalid use of SingleClientConnManager: connection still allocated和Lars Vogel Apache HttpClient - Tutorial):
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);