我使用 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());
}
最佳答案
为了在您的代码中使用单个客户端(基于 Exception using HttpRequest.execute(): Invalid use of SingleClientConnManager: connection still allocated 和 Lars Vogel Apache HttpClient - Tutorial ):
- 第 1 步。将客户端生成移到
for 循环
之外。 第 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();
}
关于java - 使用 httpclient 的连接持久性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15105647/