博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
httpclient调用https
阅读量:7118 次
发布时间:2019-06-28

本文共 10231 字,大约阅读时间需要 34 分钟。

httpclient调用https报错:

Exception in thread "main" java.lang.Exception: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: timestamp check failed

 

代码:

package com.taiping;import java.io.BufferedReader;import java.io.DataInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.net.URLEncoder;import java.util.Map;import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpException;import org.apache.commons.httpclient.HttpStatus;import org.apache.commons.httpclient.NameValuePair;import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.methods.StringRequestEntity;import org.apache.commons.httpclient.params.HttpMethodParams;import org.apache.commons.httpclient.protocol.Protocol;import com.taiping.base.facility.tool.JAXBTool;import com.taiping.base.util.IOTool;import com.taiping.partner.antgroup.DTO.ali.request.RequestCheckDoc;import com.taiping.partner.antgroup.DTO.ali.request.RequestCheckbillDoc;import com.taiping.z.HTTPSSecureProtocolSocketFactory;public class HttpXmlSender_189_1_LOCAL{    public static void main(String[] args) throws Exception    {        // 核保:"test-antgroup-underwrite-12602-5.xml";        // 出单:"test-antgroup-issue-12602-5.xml";  test-antgroup-issue-EBB.xml test-antgroup-issue-YaZhouLYYW.xml        String file = "test-antgroup-underwrite-EBB.xml";                String path = HttpXmlSender_189_1_LOCAL.class.getResource("/template/"+file).getPath();        System.out.println("path : "+path);                // 请确认编码方式        String encode = "utf-8";        String xml = IOTool.readFile(path, encode);  //请确认编码方式                // localhost本地//        String url = "http://localhost:8000/taiping-sol-mall/services/antgroup/entrance";        // UAT环境        String url = "https://baoxian.itaiping.com/services/antgroup/entrance";//        String url = "http://10.1.17.95:7002/services/antgroup/entrance";            // 生产环境//        String url = "http://baoxian.cntaiping.com/partner/partnerEntrance.action";        // 生产环境IP访问//        String url = "http://10.4.233.6:8003/partner/partnerEntrance.action";                String policyNo ="2016ANTGROUP_XLH08171";        xml = xml.replaceAll("#policyNo#", policyNo);                // 1、解析报文        RequestCheckDoc requestCheckDoc = null;        RequestCheckbillDoc requestCheckbillDoc = null;        try {            if (xml.indexOf("underwrite") > -1) {                requestCheckDoc = (RequestCheckDoc) JAXBTool.unmarshal(xml, RequestCheckDoc.class);                requestCheckDoc.setSignature();                xml = JAXBTool.marshal(requestCheckDoc);            }else {                requestCheckbillDoc = (RequestCheckbillDoc) JAXBTool.unmarshal(xml, RequestCheckbillDoc.class);                requestCheckbillDoc.setSignature();                xml = JAXBTool.marshal(requestCheckbillDoc);            }            System.out.println("requestXml:\n"+xml);        } catch (Exception e) {            e.printStackTrace();        }                String responseXml = new HttpXmlSender_189_1_LOCAL().post(url,xml,encode,policyNo);        System.out.println("responseXml:\n"+responseXml);    }    /**     * post 方法     * @param  url     * @param params     * @return     */    public String post(String url, Object content, String encode,String policyNo) throws Exception {                String responseMsg = "";        byte[] responseBody = null;        HttpClient httpclient = new HttpClient();                // 为支持https step1        Protocol https = new Protocol("https", new HTTPSSecureProtocolSocketFactory(), 443);        Protocol.registerProtocol("https", https);                PostMethod httpPost = new PostMethod(url);        httpPost.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK");        httpPost.setRequestHeader("ContentType", "application/xml;charset=GBK");        // 设置连接超时时间(单位毫秒)        httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(6000000);        // 设置读数据超时时间(单位毫秒)                httpclient.getHttpConnectionManager().getParams().setSoTimeout(6000000);        try {            httpPost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, false));            // servlet            if (content instanceof Map) {                @SuppressWarnings("unchecked")                Map
map = (Map
)content; NameValuePair[] param = new NameValuePair[map.size()]; int index = 0; for (Map.Entry
entry : map.entrySet()) { param[index] = new NameValuePair(entry.getKey(),URLEncoder.encode(entry.getValue(), "GBK")); } httpPost.setRequestBody(param); } // rest else { httpPost.setRequestEntity(new StringRequestEntity((String)content,"application/xml", encode));// System.out.println("=========================================================");// System.out.println("request by rest ......"); } // post int statusCode = httpclient.executeMethod(httpPost); // 为支持https step1 over Protocol.unregisterProtocol("https"); System.out.println("policyNo:"+policyNo+",statusCode:"+statusCode); // success if (statusCode == HttpStatus.SC_OK) { responseBody = httpPost.getResponseBody(); } // failure else { responseMsg = String.valueOf("statusCode:"+statusCode); } } catch (HttpException e) { throw new Exception(e.getMessage()); } catch (IOException e) { throw new Exception(e.getMessage()); } catch (Exception e) { throw new Exception(e.getMessage()); } finally { httpPost.releaseConnection(); } if (responseBody != null) { responseMsg = new String(responseBody, encode); } return responseMsg; }}
HTTPSSecureProtocolSocketFactory:
package com.taiping.z;import java.io.IOException;  import java.net.InetAddress;  import java.net.InetSocketAddress;  import java.net.Socket;  import java.net.SocketAddress;  import java.net.UnknownHostException;  import java.security.KeyManagementException;  import java.security.NoSuchAlgorithmException;  import java.security.cert.CertificateException;  import java.security.cert.X509Certificate;  import javax.net.SocketFactory;  import javax.net.ssl.SSLContext;  import javax.net.ssl.TrustManager;  import javax.net.ssl.X509TrustManager;  import org.apache.commons.httpclient.ConnectTimeoutException;  import org.apache.commons.httpclient.params.HttpConnectionParams;  import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;  /**  * httpclient https  *  */  public class HTTPSSecureProtocolSocketFactory implements ProtocolSocketFactory {
//SecureProtocolSocketFactory private SSLContext sslcontext = null; private SSLContext createSSLContext() { SSLContext sslcontext = null; try { sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return sslcontext; } private SSLContext getSSLContext() { if (null == this.sslcontext) { this.sslcontext = createSSLContext(); } return this.sslcontext; } public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); } public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(host, port); } public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort); } public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); SocketFactory socketfactory = getSSLContext().getSocketFactory(); if (timeout == 0) { return socketfactory.createSocket(host, port, localAddress, localPort); } else { Socket socket = socketfactory.createSocket(); SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); socket.bind(localaddr); socket.connect(remoteaddr, timeout); return socket; } } private static class TrustAnyTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } } }

 

转载地址:http://wiiel.baihongyu.com/

你可能感兴趣的文章
站长必知的八大社会心理学效应
查看>>
开源云平台 CloudStack 4.1.0 安装详解 - 3、vCenter
查看>>
系统技巧之如何巧妙的整理磁盘碎片
查看>>
点击APPicon之后都发生了什么
查看>>
油价下降,全国人民都高兴
查看>>
mac10.14.1回收windows系统盘
查看>>
js 获取子节点个数
查看>>
jquery的颜色选择插件实例代码
查看>>
android ListView详解
查看>>
顶级MySQL主从复制企业应用
查看>>
OVS-vsctl的帮助文件的中文版
查看>>
我的友情链接
查看>>
《神探tcpdump第五招》-linux命令五分钟系列之三十九
查看>>
《回答sort一例》-linux命令五分钟系列之二十八
查看>>
稳坐视频云行业第一,阿里云将用边缘计算开辟新赛道
查看>>
转载杂项集
查看>>
oracle libary cache 命中率
查看>>
每天一个linux命令(23):Linux 目录结构
查看>>
数据库Sharding的基本思想和切分策略
查看>>
我的友情链接
查看>>