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

扶醉桌前 提交于 2019-12-21 03:39:20

问题


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?


回答1:


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();



回答2:


I can not comment yet, but here is a small upgrade to herau's answer since it's deprecated since 4.4, maybe someone will find it useful.

SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);



回答3:


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

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


来源:https://stackoverflow.com/questions/23201648/httpclient-4-3-x-fixing-deprecated-code-to-use-current-httpclient-implementatio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!