Apache HttpComponents HttpClient 超时

如何在 httpcomponents httpclient 中设置连接超时?我在以下位置找到了文档:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html 但不清楚这些参数的实际设置方式。

此外,解释和之间的区别会有所帮助。SO_TIMEOUTCONNECTION_TIMEOUT


答案 1

在 Apache Http Client 的 4.3 版中,配置被重构(再次)。新方式如下所示:

RequestConfig.Builder requestBuilder = RequestConfig.custom();
requestBuilder.setConnectTimeout(timeout);
requestBuilder.setConnectionRequestTimeout(timeout);

HttpClientBuilder builder = HttpClientBuilder.create();     
builder.setDefaultRequestConfig(requestBuilder.build());
HttpClient client = builder.build();

答案 2

在 HttpClient 4.3 版本中,您可以使用以下示例。让我们说5秒钟

int timeout = 5;
RequestConfig config = RequestConfig.custom()
  .setConnectTimeout(timeout * 1000)
  .setConnectionRequestTimeout(timeout * 1000)
  .setSocketTimeout(timeout * 1000).build();
CloseableHttpClient client = 
  HttpClientBuilder.create().setDefaultRequestConfig(config).build();
HttpGet request = new HttpGet("http://localhost:8080/service"); // GET Request
response = client.execute(request);

推荐