HttpClient调用Https服务(不校验服务器证书)

HttpClient调用Https服务(不校验服务器证书)

  • 1. POM引入
  • 2. 代码实现

1. POM引入


<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpclientartifactId>
    <version>4.5.12version>
dependency>

2. 代码实现

@Test
public void invoke_https_without_certificate_verification()
        throws Exception {
    // 创建SSL Context,信任所有的Server证书
    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(null, (certificate, authType) -> true).build();

    // 创建HttpClient
    CloseableHttpClient client = HttpClients.custom()
            .setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .build();

    // 设置Header、调用Https服务
    String urlOverHttps = "https://localhost:443/index";
    HttpGet httpGet = new HttpGet(urlOverHttps);
    httpGet.setHeader("Accept", "application/xml");
    HttpResponse response = client.execute(httpGet);

    // 校验响应状态码
    assertEquals(response.getStatusLine().getStatusCode(), 200);
}

你可能感兴趣的:(PKI)