如何使用Apache httpcomponent5设置Spring HttpComponentsClientHttpRequestFactory?

70gysomp  于 2022-11-28  发布在  Spring
关注(0)|答案(2)|浏览(449)

下面的代码是一个很好的例子:

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?

w6lpcovy

w6lpcovy1#

Apache HttpClient 4.5和HttpClient 5.0 classic非常相似,但API * 完全不兼容 *。
在Spring提供基于Apache HttpClient 5.x的RequestFactory实现之前,无法将HttpClient 5.x与Spring集成。

相关问题