java - 使用 httpclient 的连接持久性

标签 java performance persistence httpclient apache-httpclient-4.x

我使用 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/

相关文章:

java - 提高应用速度的技巧

java - LibGDX Sprite 渲染问题

java - 'log'/时间序列的高可靠存储

c - 你为什么用汇编编程?

nosql - 用于聊天历史持久化和用户统计的 CouchDB

java - 手动管理持久性上下文的技巧

java - 自定义 JScrollPane 中的 JRadioButtons 未出现?

java - 未找到 int 数组中的元素(虽然应该找到)

MySQL:连接与按位运算符及其性能

performance - 有什么方法可以在 PostgreSQL 中使用 >1 Core 进行单个连接/查询?