javax.net.ssl.SSLException:证书中的主机名没有匹配

时间:2016-04-17 14:11:02

标签: java android ssl

我的Android应用告诉我,我的https证书与主机名不匹配:

javax.net.ssl.SSLException: hostname in certificate didn't match: <hostname1> != <oldhostname>

奇怪的是

  1. 网站( hostname1 )提供正确的证书(使用浏览器和ssllabs工具检查)
  2. oldhostname 是我在之前版本的应用中设置的先前主机名
  3. 是否有某种证书缓存?我找不到任何关于

    的信息

1 个答案:

答案 0 :(得分:0)

添加此课程

public class HttpsTrustManager implements X509TrustManager {
    private static TrustManager[] trustManagers;
    private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};

    @Override
    public void checkClientTrusted(
            X509Certificate[] x509Certificates, String s)
            throws java.security.cert.CertificateException {
    }

    @Override
    public void checkServerTrusted(
            X509Certificate[] x509Certificates, String s)
            throws java.security.cert.CertificateException {
    }

    public boolean isClientTrusted(X509Certificate[] chain) {
        return true;
    }

    public boolean isServerTrusted(X509Certificate[] chain) {
        return true;
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return _AcceptedIssuers;
    }

    public static void allowAllSSL() {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }

        });

        SSLContext context = null;
        if (trustManagers == null) {
            trustManagers = new TrustManager[]{new HttpsTrustManager()};
        }

        try {
            context = SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }

        HttpsURLConnection.setDefaultSSLSocketFactory(context != null ? context.getSocketFactory() : null);
    }
}

并使用HttpsTrustManager.allowAllSSL();

从您的MainActivity中调用它

虽然这不是保存方法,但我解决了我的问题。