Java-HTTPClient实现HTTPS请求

目前只实现了https的GET请求,后续还会继续更新

一、GET请求

public static void submitGet() {
		
		try {
			//显示https握手过程,方便调试
//			System.setProperty("javax.net.debug", "all");
			
			//调试双向认证使用,暂不使用
			SSLContext sslcontext = SSLContexts.custom()
                    .loadTrustMaterial(new File("D:\\Java\\jdkSE-8u201\\bin\\steven.keystore"), "123456".toCharArray(),
                            new TrustSelfSignedStrategy())
                    .build();
			
			// 证书全部信任 不做身份鉴定
			SSLContextBuilder builder = new SSLContextBuilder();
			builder.loadTrustMaterial(null, new TrustStrategy() {

				@Override
				public boolean isTrusted(X509Certificate[] ax509certificate,
						String s) throws CertificateException {
					// TODO Auto-generated method stub
					return true;
				}
			});
			
			//使用谷歌浏览器查看网页使用的是哪一个SSL协议,SSLv2Hello需要删掉,不然会报握手失败,具体原因还不知道
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new String[] {
					"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2" }, null,
					NoopHostnameVerifier.INSTANCE);
			
			Registry registry = RegistryBuilder
					. create()
					.register("http", new PlainConnectionSocketFactory())
					.register("https", sslsf).build();
			
			PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
			cm.setMaxTotal(200);// max connection
			
			
			CloseableHttpClient client = HttpClients.custom()
					.setSSLSocketFactory(sslsf).setConnectionManager(cm)
					.setConnectionManagerShared(true).build();
			//开始设置请求相关信息
			HttpGet httpGet = new HttpGet("https://192.168.1.245/test/pages/login.jsp");
			CloseableHttpResponse response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			if(entity != null) {
				System.out.println("长度:" + entity.getContentLength());
				System.out.println("内容:" + EntityUtils.toString(entity, "gbk"));
			}
			response.close();
			client.close();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeyStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (CertificateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

 

相关扩展

错误1:javax.net.ssl.SSLException: Received fatal alert: protocol_version

可以在代码中添加:System.setProperty("javax.net.debug", "all");打印握手过程,帮助分析

查看客户端网页使用的哪个ssl,我用的谷歌看的

Java-HTTPClient实现HTTPS请求_第1张图片

错误2:java.net.ConnectException: Connection refused: connect

服务器没有启动

错误3:.javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed

服务端证书不可信

错误4:java.net.SocketException: Software caused connection abort: recv failed

服务端是双向认证,客户端发送的是单向认证,没有将客户端证书一起发送

错误5:org.apache.commons.httpclient.NoHttpResponseException

一般是服务端防火墙拦截,也有可能是负载过重

错误6:javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake

这是由于服务端配置的是SSL双向认证,而客户端发送数据是按照服务器是单向认证时发送的,即没有将客户端证书信息一起发送给服务端。服务端验证客户端证书时,发现客户端没有证书,然后就断开了握手连接。

参考资料:

https://blog.csdn.net/coqcnbkggnscf062/article/details/79812102

https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java

Java-HTTPClient实现HTTPS请求_第2张图片

 

你可能感兴趣的:(java基础)