java http 客戶端使用TSLv1.2[解決Remote host closed connection during handshake的問題]
阿新 • • 發佈:2018-10-31
1. jdk1.7預設是TSLv1, 但是可以支援TSLv1.1,TSLv1.2,jdk1.8預設是TSLv1.2
2.如果客服端是TSLv1,伺服器端設定是TSLv1.2,訪問會出現connection reset的錯誤.
3.既然jdk1.7可以支援TSLv1.2那麼肯定有辦法設定。網上找了好久,查詢谷姐資料看說法最多的是加入jvm啟動引數: -Dhttps.protocols=TLSv1.1,TLSv1.2 但是我試了沒有用,還是報錯。
4.用java程式查詢自己當前程式預設支援的SSL/TSL版本的方法。
public static void main(String[] args) throws Exception { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, null, null); SSLSocketFactory factory = (SSLSocketFactory) context.getSocketFactory(); SSLSocket socket = (SSLSocket) factory.createSocket(); String[] protocols = socket.getSupportedProtocols(); System.out.println("Supported Protocols: " + protocols.length); for (int i = 0; i < protocols.length; i++) { System.out.println(" " + protocols[i]); } protocols = socket.getEnabledProtocols(); System.out.println("Enabled Protocols: " + protocols.length); for (int i = 0; i < protocols.length; i++) { System.out.println(" " + protocols[i]); } }
5.通過GUI查詢自己javaTSL版本。
①.開啟Java Control Panel.
②.高階。拉到最下面。
6.關門,放程式碼。繼承import org.apache.http.impl.client.DefaultHttpClient;類,改了一點東西,使用的時候用SSLClien就好了。
import org.apache.http.impl.client.DefaultHttpClient; public class SSLClient extends DefaultHttpClient { public SSLClient() throws Exception { super(); SSLContext ctx = SSLContext.getInstance("TLSv1.2"); X509TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certi<a target=_blank target="_blank" href="http://superuser.com/questions/747377/enable-tls-1-1-and-1-2-for-clients-on-java-7">http://superuser.com/questions/747377/enable-tls-1-1-and-1-2-for-clients-on-java-7</a>ficate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); org.apache.http.conn.ssl.SSLSocketFactory ssf = new org.apache.http.conn.ssl.SSLSocketFactory(ctx, org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = this.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); } }
7.如果你覺得本文章有用並且對你有幫助,請用支付寶掃描下面的二維碼給我打賞。一塊兩塊不嫌少,一千兩千不嫌多。,
8.參考
②.http://superuser.com/questions/747377/enable-tls-1-1-and-1-2-for-clients-on-java-7