httpclient调用https

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:
"+xml);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        String responseXml = new HttpXmlSender_189_1_LOCAL().post(url,xml,encode,policyNo);
        System.out.println("responseXml:
"+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<String, String> map = (Map<String, String>)content;
                NameValuePair[] param = new NameValuePair[map.size()];
                
                int index = 0;
                for (Map.Entry<String, String> 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