3

我使用 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());
}
4

2 回答 2

8

为了在您的代码中使用单个客户端(基于Exception using HttpRequest.execute(): Invalid use of SingleClientConnManager: connection still assigned和 Lars Vogel 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();
}
于 2013-02-27T06:59:56.030 回答
0

试试下面。

HttpUriRequest httpGet = new HttpGet(uri);
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
于 2013-02-27T06:53:52.893 回答