轉:https://blog.csdn.net/xtj332/article/details/52228351
java http 客戶端使用TSLv1.2[解決Remote host closed connection during handshake的問題]
2016年08月17日 10:40:07 freewind 閱讀數:34681更多
1. jdk1.7默認是TSLv1, 可是能夠支持TSLv1.1,TSLv1.2,jdk1.8默認是TSLv1.2spa
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 {
-
-
SSLContext ctx = SSLContext.getInstance(
"TLSv1.2");
-
X509TrustManager tm =
new X509TrustManager() {
-
-
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 {
-
-
-
-
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
-
-
-
-
public X509Certificate[] getAcceptedIssuers() {
-
-
-
-
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.若是你以爲本文章有用而且對你有幫助,請用支付寶掃描下面的二維碼給我打賞。一塊兩塊不嫌少,一千兩千不嫌多。
,