2015年10月30日 星期五

在 Apache HttpClient 4.5 版忽略 HTTPS 認證

一般 HTTPS 連線會驗證包括證書本身以及像是 host name 等資訊
不過在測試階段時,有時會因為證書是用自我驗證來產生的,導致程式碼無法正常運作
HttpClient 有設定方法可以忽略這些認證資訊~
不過在 HttpClient 4.3 版以後,陸續有些類別和方法都被廢棄了
以下是在 HttpClient 4.5 版的設定方法。


CloseableHttpClient HTTP_CLIENT = null;
try {
	// TODO Ignore the SSL certificate and host name verifier which should not be ignored in production.
	SSLContextBuilder sslBuilder = new SSLContextBuilder();
	sslBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
	SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
			sslBuilder.build(), 
			new TrustAllHostNameVerifier());
		
	HTTP_CLIENT = HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
	e.printStackTrace();
}
其中 TrustAllHostNameVerifier 這個類別的宣告如下:
private static class TrustAllHostNameVerifier implements HostnameVerifier {
	public boolean verify(String hostname, SSLSession session) {
		return true;
	}
}
另外 SSLContextBuilder 的完整類別名稱是 org.apache.http.ssl.SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder 已被廢棄)

參考資料:
  1. Java SSLException: hostname in certificate didn't match
  2. Getting Java to accept all certs over HTTPS

沒有留言: