通常,開發人員將在本地機器上或專案的開發階段使用自簽名證書。 預設情況下,HttpClient(和Web瀏覽器)不會接受不可信的連線。 但是,可以組態HttpClient
以允許不可信的自簽名證書。
注意:這是一個可能存在安全風險,因為您將其用於生產時,基本上會禁用所有的認證檢查,這可通導致受到攻擊。
在這個例子中,我們演示了如何忽略Apache HttpClient 4.5中的SSL / TLS證書錯誤。
當您嘗試向使用自簽名證書的伺服器發出請求並且證書未被用戶端知曉時,將收到以下異常 -
Caused by:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
我們使用maven來管理依賴關係,並使用Apache HttpClient 4.5版本。 將以下依賴項新增到您的專案中。
pom.xml 檔案的內容如下 -
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yiibai.httpclient.httmethods</groupId>
<artifactId>http-get</artifactId>
<version>1.0.0-SNAPSHOT</version>
<url>https://memorynotfound.com</url>
<name>httpclient - ${project.artifactId}</name>
<dependencies>
<!-- Apache Commons IO -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
我們組態一個自定義的HttpClient。 首先使用SSLContextBuilder
設定SSLContext並使用TrustSelfSignedStrategy
類來允許自簽名證書。 使用NoopHostnameVerifier
本質上關閉主機名驗證。 建立SSLConnectionSocketFactory
並傳入SSLContext和HostNameVerifier
,並使用工廠方法構建HttpClient。
檔案:HttpClientAcceptSelfSignedCertificate.java -
package com.yiibai.httpdemo;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.*;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import javax.net.ssl.*;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
/**
* This example demonstrates how to ignore certificate errors.
* These errors include self signed certificate errors and hostname verification errors.
*/
public class HttpClientAcceptSelfSignedCertificate {
public static void main(String... args) {
try (CloseableHttpClient httpclient = createAcceptSelfSignedCertificateClient()) {
HttpGet httpget = new HttpGet("https://www.tw511.com");
System.out.println("Executing request " + httpget.getRequestLine());
httpclient.execute(httpget);
System.out.println("----------------------------------------");
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | IOException e) {
throw new RuntimeException(e);
}
}
private static CloseableHttpClient createAcceptSelfSignedCertificateClient()
throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
// use the TrustSelfSignedStrategy to allow Self Signed Certificates
SSLContext sslContext = SSLContextBuilder
.create()
.loadTrustMaterial(new TrustSelfSignedStrategy())
.build();
// we can optionally disable hostname verification.
// if you don't want to further weaken the security, you don't have to include this.
HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
// create an SSL Socket Factory to use the SSLContext with the trust self signed certificate strategy
// and allow all hosts verifier.
SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);
// finally create the HttpClient using HttpClient factory methods and assign the ssl socket factory
return HttpClients
.custom()
.setSSLSocketFactory(connectionFactory)
.build();
}
}
執行上面範例程式碼,得到以下結果 -
Executing request GET https://www.tw511.com HTTP/1.1
----------------------------------------