Https请求忽略证书验证最新实现

最近工作中需要和一个第三方公司进行https交互请求,但是对方的证书有一些问题,所以在发送请求的时候需要忽略证书验证。百度之后,发现已经有很多这方面的介绍,不过在使用其代码的时候总会有一些类不推荐使用了。下面是参考网上的常见方面并结合最新的官方API实现的一个最新方法(使用的主要jar包括httpclient-4.5.1.jar和httpcore-4.4.3.jar)。

	public static List doPostByClient(String url, Map<?, ?> postData, Map<?, ?> header,
			String encoding, long connectionTimeout, long soTimeout,boolean isNoSSL)
			throws Exception {

		CloseableHttpClient client = HttpClients.createDefault();
		if(isNoSSL)
		{
			client = (CloseableHttpClient)wrapClient(client);
		}

		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout((int) soTimeout).setConnectTimeout((int) connectionTimeout).build();//设置请求和传输超时时
		httpPost.setConfig(requestConfig);

		// 头部请求信息
		if (header != null) {
			Set<?> entrySet = header.entrySet();
			for (Iterator<?> itor = entrySet.iterator(); itor.hasNext();) {
				Map.Entry entry = (Map.Entry) itor.next();
				httpPost.addHeader(entry.getKey().toString(), entry.getValue()
						.toString());
			}
		}

		List<NameValuePair> parameters = new ArrayList<NameValuePair>();

		if (postData != null) {

			Set<?> entrySet = postData.entrySet();

			for (Iterator<?> itor = entrySet.iterator(); itor.hasNext();) {

				Map.Entry entry = (Map.Entry) itor.next();

				parameters.add(new BasicNameValuePair(
						entry.getKey().toString(), entry.getValue() + ""));

			}

			// 创建UrlEncodedFormEntity对象
			UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(
					parameters, encoding);
			
			httpPost.setEntity(formEntiry);
		}

		// 执行请求

		HttpResponse response = client.execute(httpPost);

		response.getStatusLine();

		StatusLine status = response.getStatusLine();

		int sc = status.getStatusCode();

		if (sc != 200) {
			return null;
		}

		HttpEntity entity = response.getEntity();

		if (entity != null) {

			InputStream is = entity.getContent();

			BufferedReader bin = new BufferedReader(new InputStreamReader(is,
					"utf-8"), 1024 * 1024);
			List result = new ArrayList();
			while (true) {
				String line = bin.readLine();
				if (line == null) {
					break;
				} else {
					result.add(line);
				}
			}
			return (result);
		} else {
			return null;
		}
	}
	
	/**
	 * 避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常
	 * 不用导入SSL证书
	 * @param base
	 * @return
	 */
	public static HttpClient wrapClient(HttpClient base) {
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509TrustManager() {
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}

				public void checkClientTrusted(X509Certificate[] arg0,
						String arg1) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] arg0,
						String arg1) throws CertificateException {
				}
			};
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx,NoopHostnameVerifier.INSTANCE);
			CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).build();
			return httpclient;
		} catch (Exception ex) {
			ex.printStackTrace();
			return HttpClients.createDefault();
		}
	}
说明:其中wrapClient方法就是创建一个不进行正式验证的请求客户端对象。

参考文档:

1.http://www.th7.cn/Program/java/201402/173791.shtml Https请求基本过程介绍;

2.http://blog.csdn.net/kobejayandy/article/details/44284765 老版本Https请求的常见实现;

3.http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/CloseableHttpClient.html  Https请求使用类的最新官方API说明。

发布了27 篇原创文章 · 获赞 4 · 访问量 13万+
展开阅读全文

C#调用https接口证书验证不通过问题

10-18

java通过证书调用https的接口,C#能实现吗?我C#尝试调用,一直报错“ssl通道建立时出现未知错误” package com.jit.szlb.util.client; import java.rmi.RemoteException; import javax.xml.namespace.QName; import javax.xml.rpc.ServiceException; import javax.xml.rpc.encoding.XMLType; import net.sf.json.JSONObject; import org.apache.axis.client.Call; import org.apache.axis.client.Service; public class TestClient { public static void main(String[] args) throws ServiceException, RemoteException { String basePath = TestClient.class.getResource("").getPath(); System.setProperty("javax.net.ssl.keyStoreType","pkcs12"); System.setProperty("javax.net.ssl.keyStore",basePath + "anjianshuju.pfx"); System.setProperty("javax.net.ssl.keyStorePassword","11111111"); System.setProperty("javax.net.ssl.trustStoreType","jks"); System.setProperty("javax.net.ssl.trustStore",basePath + "127.0.0.1.jks"); System.setProperty("javax.net.ssl.trustStorePassword","11111111"); Service service=new Service(); Call call=(Call)service.createCall(); call.setTargetEndpointAddress("https://139.215.205.50/iservice/webservice/iservice?wsdl"); call.setSOAPActionURI("http://service.jkfwpt.jit.com/serverService"); call.setUseSOAPAction(true); call.setOperationName(new QName("http://service.jkfwpt.jit.com/", "serverService")); call.setReturnType(XMLType.XSD_STRING); call.addParameter("xtid", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN); call.addParameter("fwid", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN); call.addParameter("param", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN); JSONObject obj = new JSONObject(); obj.put("queryCode", "mg0412kv"); String str = (String)call.invoke(new Object[]{"8a81a7c5576583be01576589ea260001","8a81a7c5576583be01576949f9d80002",""}); System.out.println(str); } } 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览