如何使用JAVA URL httpsconnection发送没有证书的https请求

时间:2015-02-20 01:38:27

标签: security ssl certificate httpconnection

我需要从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 sun.security.ssl.Alerts.getSSLException(Alerts.java:192)

这是我的代码:

URL obj = new URL(url);
HttpsURLConnection con =  (HttpsURLConnection) obj.openConnection();
con.setHostnameVerifier(new AlwaysTrustHostnameVerifier());

class AlwaysTrustHostnameVerifier implements X509TrustManager, HostnameVerifier 
{
   @Override
    public void checkClientTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {
        // TODO Auto-generated method stub

    }
    @Override
    public void checkServerTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {
        // TODO Auto-generated method stub

    }
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public boolean verify(String arg0, SSLSession arg1) {
        // TODO Auto-generated method stub
        return false;
    }      
} 

所以我不知道我是否可以在不安装安全证书的情况下检索或发布到https网址?我曾经使用NodeJS / PHP,都可行,只需通过添加一些标题信息来忽略错误,例如rejectUnauthorized为false ......

Java中是否有任何解决方法可以让我在不必安装安全证书的情况下向https发送请求?

由于

1 个答案:

答案 0 :(得分:0)

这是openJDK中的bug,您可能需要获取openJDK的最新修订版本或移至OracleJDK。