java http 客户端使用TSLv1.2[解决Remote host closed connection during handshake的问题]

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://stackoverflow.com/questions/21245796/javax-net-ssl-sslhandshakeexception-remote-host-closed-connection-during-handsh 

   ②.http://superuser.com/questions/747377/enable-tls-1-1-and-1-2-for-clients-on-java-7

   ③.https://blogs.oracle.com/java-platform-group/entry/java_8_will_use_tls

猜你喜欢

转载自blog.csdn.net/xtj332/article/details/52228351