简体   繁体   中英

HttpClient 4.3.x, fixing deprecated code to use current HttpClient implementations

I had the following code, which still compiles, but they're all deprecated:

SSLSocketFactory sslSocketFactory = new SSLSocketFactory(context, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager clientConnectionManager = base.getConnectionManager();
SchemeRegistry schemeRegistry = clientConnectionManager.getSchemeRegistry();
schemeRegistry.register(new Scheme("https", 443, sslSocketFactory));
return new DefaultHttpClient(clientConnectionManager, base.getParams());

I tried my best to replace it with this portion of the code:

HttpClientBuilder builder = HttpClientBuilder.create();
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(context, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
builder.setConnectionManager(new BasicHttpClientConnectionManager());
builder.setSSLSocketFactory(sslConnectionFactory);
return builder.build();

As you can see, there are few lines of code from the top post that I don't know how to include on the new portion. How can I add needed code, such as, an alternate SchemeRegistry ?

我还不能发表评论,但这里是 herau 答案的一个小升级,因为它自 4.4 以来已被弃用,也许有人会发现它很有用。

SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);
HttpClientBuilder builder = HttpClientBuilder.create();
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(context, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
builder.setSSLSocketFactory(sslConnectionFactory);

Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
        .register("https", sslConnectionFactory)
        .build();

HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);

builder.setConnectionManager(ccm);

return builder.build();

As manual said, I have replaced library to NoopHostnameVerifier and use it like that:

    private static CloseableHttpClient client =
        HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM