下面的代码是一个很好的例子:
PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(SSLConnectionSocketFactoryBuilder.create()
.setSslContext(SSLContexts.createSystemDefault())
.setTlsVersions(TLS.V_1_3, TLS.V_1_2)
.build())
.setDefaultSocketConfig(SocketConfig.custom()
.setSoTimeout(Timeout.ofSeconds(5))
.build())
.setPoolConcurrencyPolicy(PoolConcurrencyPolicy.STRICT)
.setConnPoolPolicy(PoolReusePolicy.LIFO)
.setConnectionTimeToLive(TimeValue.ofMinutes(1L))
.build();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectTimeout(Timeout.ofSeconds(5))
.setResponseTimeout(Timeout.ofSeconds(5))
.setCookieSpec(StandardCookieSpec.STRICT)
.build())
.build();
CookieStore cookieStore = new BasicCookieStore();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
HttpClientContext clientContext = HttpClientContext.create();
clientContext.setCookieStore(cookieStore);
clientContext.setCredentialsProvider(credentialsProvider);
clientContext.setRequestConfig(RequestConfig.custom()
.setConnectTimeout(Timeout.ofSeconds(5000))
.setResponseTimeout(Timeout.ofSeconds(5000))
.build());
// connect Spring httpComponent (client-side) with Apache httpClient
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setReadTimeout(60000);
httpRequestFactory.setConnectTimeout(60000);
httpRequestFactory.setHttpClient(client);
类ClosableHttpClient实现了与setHttpClient(客户端)不兼容的接口org.apache.hc.client5.http.classic.HttpClient;这是运行时错误:
java.lang.ClassCastException: class org.apache.hc.client5.http.impl.classic.InternalHttpClient cannot be cast to class org.apache.http.client.HttpClient (org.apache.hc.client5.http.impl.classic.InternalHttpClient and org.apache.http.client.HttpClient are in unnamed module of loader 'app')
我正在使用Spring 5.0和HttpComponents-client-5。如何将HttpClient 4.X转换为HttpClient 5?
2条答案
按热度按时间w6lpcovy1#
Apache HttpClient 4.5和HttpClient 5.0 classic非常相似,但API * 完全不兼容 *。
在Spring提供基于Apache HttpClient 5.x的
RequestFactory
实现之前,无法将HttpClient 5.x与Spring集成。qkf9rpyu2#
注意:需要Apache HttpComponents 5.1或更高版本(自Spring 6.0起)。
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/client/HttpComponentsClientHttpRequestFactory.html