使用RestTemplate訪問https實現SSL請求操作
方法1: 用java生成證書,不建議,移植性差。
方法2: 將RestTemplate改為https請求。
1、添加HttpsClientRequestFactory工具類
import org.springframework.http.client.SimpleClientHttpRequestFactory; import javax.net.ssl.*; import java.io.IOException; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.Socket; import java.security.cert.X509Certificate; /** * TLS的三個作用: * (1)身份認證 * 通過證書認證來確認對方的身份,防止中間人攻擊 * (2)數據私密性 * 使用對稱性密鑰加密傳輸的數據,由於密鑰隻有客戶端/服務端有,其他人無法窺探。 * (3)數據完整性 * 使用摘要算法對報文進行計算,收到消息後校驗該值防止數據被篡改或丟失。 * * 使用RestTemplate進行HTTPS請求訪問: * private static RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory()); * */ public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory { @Override protected void prepareConnection(HttpURLConnection connection, String httpMethod) { try { if (!(connection instanceof HttpsURLConnection)) { throw new RuntimeException("An instance of HttpsURLConnection is expected"); } HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory())); httpsConnection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); super.prepareConnection(httpsConnection, httpMethod); } catch (Exception e) { e.printStackTrace(); } } private static class MyCustomSSLSocketFactory extends SSLSocketFactory { private final SSLSocketFactory delegate; public MyCustomSSLSocketFactory(SSLSocketFactory delegate) { this.delegate = delegate; } // 返回默認啟用的密碼套件。除非一個列表啟用,對SSL連接的握手會使用這些密碼套件。 // 這些默認的服務的最低質量要求保密保護和服務器身份驗證 @Override public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); } // 返回的密碼套件可用於SSL連接啟用的名字 @Override public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); } @Override public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException { final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose); return overrideProtocol(underlyingSocket); } @Override public Socket createSocket(final String host, final int port) throws IOException { final Socket underlyingSocket = delegate.createSocket(host, port); return overrideProtocol(underlyingSocket); } @Override public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort) throws IOException { final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort); return overrideProtocol(underlyingSocket); } @Override public Socket createSocket(final InetAddress host, final int port) throws IOException { final Socket underlyingSocket = delegate.createSocket(host, port); return overrideProtocol(underlyingSocket); } @Override public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress, final int localPort) throws IOException { final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort); return overrideProtocol(underlyingSocket); } private Socket overrideProtocol(final Socket socket) { if (!(socket instanceof SSLSocket)) { throw new RuntimeException("An instance of SSLSocket is expected"); } //((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1.2"}); ((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"}); return socket; } } }
註意:服務端TLS版本要和客戶端工具類中定義的一致。(TLSv1.2)
2、修改RestTemplate
在使用的時候,將
private static RestTemplate restTemplate = new RestTemplate();
改為:
private static RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
其他代碼不變。
也可使用註入的方式:
@Configuration public class ConfigBean { @Bean public RestTemplate getRestTemplate() { return new RestTemplate(new HttpsClientRequestFactory()); } }
3、訪問https,拋出的異常
javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure解決方案
因為jdk中jce的安全機制導致報的錯,需要去oracle官網下載對應的jce包替換jdk中的jce包。
方案一:替換jce包
目錄 %JAVA_HOME%\jre\lib\security裡的local_policy.jar,US_export_policy.jar JDK7 http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html JDK8 http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html // pub1:/home/myron/jdk1.7.0_80 % cd $JAVA_HOME/jre/lib/security/ //jce所在jdk的路徑 US_export_policy.jar local_policy.jar
方案二:升級 JDK到1.8版本(推薦方式)
// pub1:/home/myron % vi .cshrc setenv JAVA_HOME /home/myron/jdk1.8.0_211 // pub1:/home/myron % source .cshrc // pub1:/home/myron % java -version java version "1.8.0_211"
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。
推薦閱讀:
- 使用Feign配置請求頭以及支持Https協議
- 使用RestTemplate調用https接口跳過證書驗證
- RestTemplate設置超時時間及返回狀態碼非200處理
- Java基於TCP協議的Socket通信
- Java Socket實現聊天室功能