Warm tip: This article is reproduced from serverfault.com, please click

java-忽略 Apache HttpClient 4.3 中的 SSL 证书

(java - Ignoring SSL certificate in Apache HttpClient 4.3)

发布于 2013-10-22 12:12:01

如何忽略Apache HttpClient 4.3 的SSL 证书(全部信任)

我在 SO 上找到的所有答案都处理以前的版本,并且 API 发生了变化。

有关的:

编辑:

  • 它仅用于测试目的。孩子们,不要在家里(或在生产中)尝试
Questioner
Jakub M.
Viewed
22
110k 2019-05-25 05:29:53

下面的代码适用于信任自签名证书。创建客户端时,你必须使用TrustSelfSignedStrategy

SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        builder.build());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
        sslsf).build();

HttpGet httpGet = new HttpGet("https://some-server");
CloseableHttpResponse response = httpclient.execute(httpGet);
try {
    System.out.println(response.getStatusLine());
    HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
} finally {
    response.close();
}

我没有SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER故意包括:重点是允许使用自签名证书进行测试,因此你不必从证书颁发机构获取适当的证书。你可以使用正确的主机名轻松创建自签名证书,因此不要添加SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER标志,而是这样做