让Java接受通过HTTPS的所有证书 [英] Getting Java to accept all certs over HTTPS

查看:154
本文介绍了让Java接受通过HTTPS的所有证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让Java通过HTTPS接受所有证书。这是出于测试目的。在我收到cert not found错误之前。但是,在我的代码之前添加以下代码后,我得到一个 HTTPS主机名错误:应该是< sub.domain.com> 错误。问题是我的网址 IS 那个网址。我该如何解决这个问题?以下是我为解决问题而添加的代码..

I'm trying to get Java to accept all certs over HTTPS. This is for testing purposes. Before I was getting a cert not found error. However, after adding the following code before my code I get a HTTPS hostname wrong: should be <sub.domain.com> error. The problem is my url IS that url. How do I get around this issue? The below is the code I've added to attempt to fix the problem..

        // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[]{
        new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
            }
        }
    };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    }


推荐答案

你需要设置一个HostNameVarifier也是
Ex:

You need to set the a HostNameVarifier also Ex:

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

public class TrustAllHostNameVerifier implements HostnameVerifier {

    public boolean verify(String hostname, SSLSession session) {
        return true;
    }

}

然后

 httpsConnection.setHostnameVerifier(new TrustAllHostNameVerifier ());

这篇关于让Java接受通过HTTPS的所有证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆