java 主动信任证书

java 主动信任证书

SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mid.toCharArray()).loadTrustMaterial(keyStore, new TrustStrategy() {
    // 信任所有
    public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType) {
        return true;
    }
}).build();

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

包: https://files.cnblogs.com/files/xiluhua/httpclient-4.3.3.zip

完整代码:

package com.taiping.dianshang.payment.service.wechat.fromWechat;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.stereotype.Component;

import com.taiping.dianshang.constant.ConstantTool;
import com.taiping.facility.cache.container.CacheContainer;
import com.taiping.facility.tool.FileStreamTool;
import com.taiping.facility.tool.LogTool;
import com.taiping.facility.tool.MapTool;
import com.taiping.facility.tool.PropertyFileTool;

/**
 * 
 * @author xilh
 * @since 20200409
 */
@Component
public class HttpclientImpl_ssl {

	/**
	 * @author xilh
	 * @since 20200324
	 */
	@SuppressWarnings({ "unchecked", "deprecation" })
	public String post(String url, Object obj, Map<String, Object> httpclientParams) throws Exception {
		HttpPost httpPost = null;
		String responseMsg = null;
		Map<String, Object> map  = (Map<String, Object>)obj;
		String trans = MapTool.getStringFromMap(map, "trans");
		String packet = MapTool.getStringFromMap(map, "packet");
		
		DefaultHttpClient httpclient = new DefaultHttpClient();
		// 代理的设置  
		String value = CacheContainer.getSystemParameterValue("internet.proxy");
		if (LogTool.isLocal) {
			value = PropertyFileTool.get("internet.proxy");
		}
		LogTool.info(this.getClass(), trans+", proxy: "+value);
		String[] arr = value.split(":");
        HttpHost proxy = new HttpHost(arr[0], Integer.valueOf(arr[1]));
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		
		try {
			// Secure Protocol implementation.
			SSLContext ctx = SSLContext.getInstance("TLS");
			// Implementation of a trust manager for X509 certificates
			X509TrustManager tm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			ClientConnectionManager ccm = httpclient.getConnectionManager();
			// register https protocol in httpclient's scheme registry
			SchemeRegistry sr = ccm.getSchemeRegistry();
			sr.register(new Scheme("https", 443, ssf));
			httpclient = new DefaultHttpClient(ccm, httpclient.getParams());
			// String auth = CacheContainer.getSysParamValue("authorization.token.18", true);
			// appKey :"TPJJ"     appSecret: "yMJlPH9RnjxpqhyysxaIXYT82U1Sh32q"
			//装配post请求参数
			httpPost = new HttpPost(url);
			httpPost.setHeader("Content-Type","application/json;charset=UTF-8");  
//	        List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
//	        list.add(new BasicNameValuePair("appKey", "TPJJ"));
//	        list.add(new BasicNameValuePair("appSecret", "yMJlPH9RnjxpqhyysxaIXYT82U1Sh32q"));
//	        list.add(new BasicNameValuePair("tokenExpireDay", "7"));
	        httpPost.setEntity(new StringEntity((String)packet,"application/json", ConstantTool.UTF8));
			HttpResponse response = httpclient.execute(httpPost);

			HttpEntity entity = response.getEntity();
			byte buffer[] = FileStreamTool.read(entity.getContent());
			LogTool.info(this.getClass(), trans+", buffer size: "+buffer.length);
			if (buffer != null && buffer.length > 0) {
				responseMsg = new String(buffer, ConstantTool.UTF8);
			}
			LogTool.info(this.getClass(), trans+", responseMsg: "+responseMsg);
			System.out.println();
		} catch (Exception e) {
			LogTool.error(this.getClass(), e);
		} finally{
			if (httpPost != null) {
				// 关闭请求
				httpPost.releaseConnection();
			}
		}

		return responseMsg;
	}
	
}

  

posted @ 2019-10-30 10:57  xiluhua  阅读(1381)  评论(0编辑  收藏  举报