HttpClient调用Https服务(不校验服务器证书)
1. POM引入
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
2. 代码实现
@Test
public void invoke_https_without_certificate_verification()
throws Exception {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (certificate, authType) -> true).build();
CloseableHttpClient client = HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
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);
}