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

本文共 10282 字,大约阅读时间需要 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[] {}; } } }

 

转载于:https://www.cnblogs.com/xiluhua/p/5780230.html

你可能感兴趣的文章
P1303 A*B Problem
查看>>
Web交互中Json的应用案例
查看>>
mysql生成日期的辅助表
查看>>
122A
查看>>
时间复杂度为O(nlogn)的LIS算法
查看>>
Java核心_Git_Maven学习[20181108]
查看>>
Python3 的递归
查看>>
jquery判断页面网址是否有效
查看>>
OC 的Runtime 消息转发机制
查看>>
单线程与多线程的简单示例(以Windows服务发短信为示例)
查看>>
Redis在win7上的可视化应用
查看>>
Linq表连接大全(INNER JOIN、LEFT OUTER JOIN、RIGHT OUTER JOIN、FULL OUTER JOIN、CROSS JOIN)
查看>>
微信小程序之转发功能(附效果图和源码)
查看>>
成熟法则
查看>>
Android 中自定义控件和属性(attr.xml,declare-styleable,TypedArray)的方法和使用
查看>>
[转]SP 2010: How To – Event Receivers and Custom Error Pages
查看>>
棋牌分布式架构
查看>>
【安卓基础】倒计时按钮封装(验证码倒计时按钮)
查看>>
configparser模块
查看>>
Crack的必备工具(2)
查看>>