常见的HttpClient,OkHttpclient,WebCl
2020-10-19 本文已影响0人
摩V羯座
1.HttpClient
PoolingHttpClientConnectionManager
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(maxTotal);
connManager.setDefaultMaxPerRoute(maxPerRoute);
超时时间配置
final RequestConfig config = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.build();
KeepAliveStrategy
ConnectionKeepAliveStrategy keepAliveStrategy = new DefaultConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(final HttpResponse response, final HttpContext context) {
long keepAlive = super.getKeepAliveDuration(response, context);
if (keepAlive == -1) {
keepAlive = defaultAliveTimeMills;
}
return keepAlive;
}
};
Retry
public DefaultHttpRequestRetryHandler(final int retryCount, final boolean requestSentRetryEnabled) {
this(retryCount, requestSentRetryEnabled, Arrays.asList(
InterruptedIOException.class,
UnknownHostException.class,
ConnectException.class,
SSLException.class));
}
Build
HttpClient httpClient = HttpClients.custom()
.setConnectionManager(connManager)
.setKeepAliveStrategy(keepAliveStrategy)
.setDefaultRequestConfig(config)
.setRetryHandler(new DefaultHttpRequestRetryHandler(3,true))
.build();
2.OkHttpClient 开箱即用
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS) //设置连接超时
.readTimeout(60, TimeUnit.SECONDS) //设置读超时
.writeTimeout(60, TimeUnit.SECONDS) //设置写超时
.retryOnConnectionFailure(true) //是否自动重连
.build();
3.WebClient 开箱即用
WebClient webClient = WebClient.builder()
.baseUrl(baseUrl)
.defaultHeader(defaultHeader)
.defaultCookie(defaultCookie).build();
总结
1.OkHttpClient 封装了HttpClient,性能类似,HttpClient可以配置更多内容,OkHttpClient使用更简单。
2.HttpClient.excute(request) 是同步非阻塞(使用HttpAsyncClient可以达到异步非阻塞),webClient是异步非阻塞,