Java HttpClient 4.3.x,修复不推荐使用的代码以使用当前的 HttpClient 实现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23201648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:17:51  来源:igfitidea点击:

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

javaapache-httpclient-4.x

提问by Buhake Sindi

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?

如您所见,顶帖中的几行代码我不知道如何包含在新部分中。如何添加所需的代码,例如替代代码SchemeRegistry

采纳答案by herau

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

回答by pitbbul

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.

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

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

回答by Krzysztof Walczewski

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

正如手册所说,我已将库替换为 NoopH​​ostnameVerifier 并像这样使用它:

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