HttpClient_javax.net.ssl.SSLHandshakeException: sun.security.validator 问题解决,与环境有关

用httpclient访问https 资源时,会出现异常,与环境也有关系,有些机器请求正常.

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1623)
        at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:198)
        at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:192)
        at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1074)
        at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:128)
        at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:529)
        at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:465)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:884)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1120)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1147)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1131)
        at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:434)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:166)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
        at com.msd.payCenter.msdPay.yeePay.util.HttpUtils.URLGet(HttpUtils.java:67)
        at com.msd.payCenter.msdPay.yeePay.service.impl.YeePayServiceImpl.yeeAutoCheckOrder(YeePayServiceImpl.java:298)
        at com.msd.payCenter.msdPay.AutoCheckOrderServiceImpl.autoCheckOrder(AutoCheckOrderServiceImpl.java:83)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1623)
        at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:198)
        at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:192)
        at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1074)
        at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:128)
        at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:529)
        at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:465)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:884)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1120)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1147)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1131)
        at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:434)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:166)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
        at com.msd.payCenter.msdPay.yeePay.util.HttpUtils.URLGet(HttpUtils.java:67)
        at com.msd.payCenter.msdPay.yeePay.service.impl.YeePayServiceImpl.yeeAutoCheckOrder(YeePayServiceImpl.java:298)
        at com.msd.payCenter.msdPay.AutoCheckOrderServiceImpl.autoCheckOrder(AutoCheckOrderServiceImpl.java:83)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

解决方法:

增加一个自己的https协议类 MySSLSocketFactory.java

package com.nassir.hc3;

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;

public class MySSLSocketFactory implements ProtocolSocketFactory {
    static {
        System.out.println(">>>>in MySSLSocketFactory>>");
    }
    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 (this.sslcontext == null) {
            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[] {};
        }
    }
}
package com.nassir.hc3;

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;

public class MySSLSocketFactory implements ProtocolSocketFactory {
    static {
        System.out.println(">>>>in MySSLSocketFactory>>");
    }
    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 (this.sslcontext == null) {
            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[] {};
        }
    }
}

请求类:

/**
 *
 */
package com.nassir.hc3;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;

/**
 * @author nassir wen
 * @data 2012-3-31 下午05:09:13
 * @version V2.5
 * @Company: MSD.
 * @Copyright Copyright (c) 2012
 */
public class HttpsRequest {

    /**
     *
     * @param url
     * @return
     */
    public static String post(String url) {
        //增加下面两行代码
        Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
        Protocol.registerProtocol("https", myhttps);

        HttpClient client = new HttpClient();
        HttpMethod post = new PostMethod(url);
        try {
            client.executeMethod(post);
            byte[] responseBody = post.getResponseBody();
            String result = new String(responseBody,"GBK");
            return result;
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            post.releaseConnection();
        }
        return null;
    }
}
/**
 *
 */
package com.nassir.hc3;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;

/**
 * @author nassir wen
 * @data 2012-3-31 下午05:09:13
 * @version V2.5
 * @Company: MSD.
 * @Copyright Copyright (c) 2012
 */
public class HttpsRequest {

    /**
     *
     * @param url
     * @return
     */
    public static String post(String url) {
        //增加下面两行代码
        Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
        Protocol.registerProtocol("https", myhttps);

        HttpClient client = new HttpClient();
        HttpMethod post = new PostMethod(url);
        try {
            client.executeMethod(post);
            byte[] responseBody = post.getResponseBody();
            String result = new String(responseBody,"GBK");
            return result;
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            post.releaseConnection();
        }
        return null;
    }
}

测试:

public static void main(String[] args) {
        System.out.println(HttpsRequest.post("https://www.alipay.com"));//支付宝做测试
    }
public static void main(String[] args) {
        System.out.println(HttpsRequest.post("https://www.alipay.com"));//支付宝做测试
    }
时间: 2024-11-05 20:39:31

HttpClient_javax.net.ssl.SSLHandshakeException: sun.security.validator 问题解决,与环境有关的相关文章

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed

使用HttpClient4.3 调用https出现如下错误: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested

mvn 编译报错mavn sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targ

mavn 编译报错: mavn sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target 解决方案: The fact is that your maven plugin try

解决 sun.security.validator.ValidatorException: PKIX path building failed

今天用java HttpClients写爬虫在访问某Https站点报如下错误: sun.security.validator.ValidatorException: PKIX path building failed... 网上找了找解决方案,看到这篇博客:http://www.oschina.net/question/12_19249 经测试,解决问题,这里做个记录.

异常解决:sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

前几天用JSOUP写爬虫Demo时,遇到这个异常 百度了一番原来是因为目标站点启用了HTTPS  而缺少安全证书时出现的异常,大概解决办法有2种: 1. 手动导入安全证书(嫌麻烦 没使用); 2. 忽略证书验证. 相对于来说简单一点,在发起请求前调用这个方法,问题解决. ``` java // 包不要导错了 import javax.net.ssl.*; import java.security.SecureRandom; import java.security.cert.Certificat

andorid HTTPS 不需要证书 VolleyEror: com.android.volley.NoConnectionError: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not fou

1.加证书(这里不说) 2.修改代码 import java.security.KeyManagementException;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.security.cert.X509Certificate;import javax.net.ssl.HostnameVerifier;import javax.net.ssl.HttpsU

解决 Java 调用 Azure SDK 证书错误 javax.net.ssl.SSLHandshakeException

Azure 作为微软的公有云平台,提供了非常丰富的 SDK 和 API 让开发人员可以非常方便的调用的各项服务,目前除了自家的 .NET.Java.Python. nodeJS.Ruby,PHP 等语言都提供支持,详细的文档说明请参考: https://azure.microsoft.com/en-us/documentation/ 然而在使用过程中,以 Java 语言为例,在初始调用 Azure SDK/API 的时候大家会碰到类似下面的错误: [WARN] ServiceBusContrac

javax.net.ssl.SSLHandshakeException

遇到证书问题:Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targetat sun

javax.net.ssl.SSLHandshakeException(Cas导入证书)

一.报错: javax.net.ssl.SSLHandshakeException 二.原因分析:CAS部署时,常常要涉及到HTTPS的证书发布问题.由于在实验环境中,CAS和应用服务常常是共用一台PC机,它们跑在相同的JRE环境和Tomcat服务器上,因此忽略了证书的实际用途,一旦将CAS和应用分别部署在不同的机器上时,就晕了! 这里假设如下实验环境来说明相应的部署  机器A: 部署CAS服务  机器B: 部署OA应用 机器C: 用户浏览器端 1.由机器A上生成.keystore的证书文件,证

转:javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure 解决方案

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure 解决方案 这个是jdk导致的,jdk里面有一个jce的包,安全性机制导致的访问https会报错,官网上有替代的jar包,换掉就好了 目录 %JAVA_HOME%\jre\lib\security里的local_policy.jar,US_export_policy.jar JDK7 http://www.oracle.com/technetwo