httpclient 使用

连接池配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
private static final int MAX_CONN_TOTAL = 500;
private static final int MAX_CONN_PER_ROUTE = 50;
private static final int TIMEOUT = 4000;
private static CloseableHttpClient client;

static {
Builder builder = RequestConfig.custom();
builder.setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT);
/*
* 4.3以上版本推荐使用HttpClientBuilder来创建client
*
* <pre>
* 1、HttpClientBuilder.setRetryHandler(HttpRequestRetryHandler retryHandler);请求重试处理。
* 2、HttpClientBuilder.setRedirectStrategy(RedirectStrategy redirectStrategy);设置重定向。
* 3、httpClientBuilder.setDefaultCookieStore(BasicCookieStore cookieStore);设置cookie store
* 4、HttpClientBuilder.setProxy(HttpHost proxy);设置代理服务器。
* 5、HttpClientBuilder.setDefaultRequestConfig(RequestConfig config);在此亦可设置RequestConfig。
* 6、HttpClientBuilder.setUserAgetn(String userAgent);设置用户代理。
* </pre>
*/
HttpClientBuilder clientBuilder = HttpClients.custom();

// 配置 SSL、TLS
// httpClientBuilder.setSSLSocketFactory(sslSocketFactory);

// builder.setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true)
// .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,
// AuthSchemes.DIGEST))
// .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC));
builder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);

RequestConfig defaultRequestConfig = builder.build();
clientBuilder.setDefaultRequestConfig(defaultRequestConfig);
// 主要连接池配置代码
// 默认是:20
clientBuilder.setMaxConnTotal(MAX_CONN_TOTAL);
// 默认是:2
clientBuilder.setMaxConnPerRoute(MAX_CONN_PER_ROUTE);

// SSL
try {
// TLS
SSLContext sc = SSLContext.getInstance("SSL");
MyX509TrustManager trustManager = new MyX509TrustManager();
sc.init(null, new TrustManager[]{trustManager}, new java.security.SecureRandom());
// 设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sc)).build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
// 主要连接池配置代码
// 默认是:20
// connManager.setMaxTotal(MAX_CONN_TOTAL);
// 默认是:2
// connManager.setDefaultMaxPerRoute(MAX_CONN_PER_ROUTE);
clientBuilder.setConnectionManager(connManager);
} catch (Exception e) {
e.printStackTrace();
}
client = clientBuilder.build();
}
  • 本文作者: forever杨
  • 本文链接: https://blog.yl-online.top/posts/812c7f75.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。如果文章内容对你有用,请记录到你的笔记中。本博客站点随时会停止服务,请不要收藏、转载!