SSL握手异常 - 链验证失败,如何解决?

81
在我的应用程序中,我尝试向服务器发送HTTPS POST请求。然而,我一直不断地收到SSLHandshakeException-链链验证失败的错误提示。我尝试使用POSTMAN发送请求,并且我从服务器上获得了响应。当我尝试从应用程序发送请求时,可能是什么原因导致这个错误?
下面是我尝试发送POST请求的代码片段:
   public static JSONObject getDataLibConfiguration(Context context) throws HttpRequestException {

    int statusCode = 0;

    JSONObject commonInformation;
    HttpsURLConnection connection = null;

    try {

        commonInformation = ConfigurationProcessor.getCommonInformation(context);
        if (commonInformation == null) {
            return null;
        }

        URL url = new URL(BuildConfig.SERVER_CONFIG_URL);
        if (BuildConfig.DEBUG) {
            LogUtils.d(TAG, "url = " + url.getPath());
        }

        connection = getHttpsConnection(url);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.setRequestProperty("Content-Encoding", "gzip");

        byte[] gzipped = HttpUtils.gzip(commonInformation.toString());
        cos = new CountingOutputStream(connection.getOutputStream()); //<-- This is where I get the exception
        cos.write(gzipped);
        cos.flush();

        statusCode = connection.getResponseCode();
        // More code her
 }

private static HttpsURLConnection getHttpsConnection(URL url) throws IOException, GeneralSecurityException {

        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            MatchDomainTrustManager myTrustManager = new MatchDomainTrustManager(url.getHost());
            TrustManager[] tms = new TrustManager[]{myTrustManager};
            sslContext.init(null, tms, null);
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            connection.setSSLSocketFactory(sslSocketFactory);
        } catch (AssertionError ex) {
            if (BuildConfig.DEBUG) {
                LogFileUtils.e(TAG, "Exception in getHttpsConnection: " + ex.getMessage());
            }
            LogUtils.e(TAG, "Exception: " + ex.toString());
        }
        return connection;
    }

LogCat 中的错误是什么? - astric mobiles
它只是说:“java.security.cert.CertificateException: 链验证失败”。 - Keselme
12个回答

221
在我的情况下,手机上的日期设置错误。
修正日期解决了问题。

2
我在安卓电视模拟器上遇到了同样的问题。更新日期并设置正确的时区解决了这个问题。 - Loïc Dumas
1
这对我来说是解决方案。我只需将日期设置为“自动”,它就可以工作了。但是有没有办法让它在“手动”日期设置下工作? - Krishnom
1
@Krishnom,如果您手动设置正确的时间,应该可以正常工作。 - Vadim
3
Android 12 模拟器出现问题的原因是相同的。对我来说,模拟器的冷启动解决了这个问题。 - Eugene Babich
13/09/2022 - 我注意到每次启动相同的模拟器时,它的日期总是设置为前一天,请务必验证一下。 - Pedro Massango
我也遇到了同样的问题,有很多手机时间都不准确,后来发现只要将日期设置为自动,问题就解决了。 - John Spax

47

如果您正在使用模拟设备,您可以尝试进行“冷启动”操作来解决问题。

有时候,这些设备上的日期会因长时间运行而停滞不前,导致证书过期问题。


34

问题在于证书已经过期。


但在我的情况下,它在几乎所有设备上都可以工作,但有些设备会收到此错误消息。 - Amin Pinjari
哪个证书?如何更新? - ahmadalibaloch
1
@ahmadalibaloch 我发送请求的服务器证书已过期,因此我必须在GoDaddy上更新它。 - Keselme
4
我的情况是,我的模拟器日期没有更新。它晚了几个星期。 - Abdulmoiz Esmail
1
这是我的第一个猜测,但不,它是错误的日期时间。很奇怪它会因为那个原因发生。 - WilliamX
在我的情况下,证书已过期。在logcat中出现了'javax.net.ssl.SSLHandshakeException: Chain validation failed'或者'Caused by: java.security.cert.CertificateExpiredException: Certificate expired at...'。 - Waseem

33

在我的情况下,我在安卓模拟器上遇到了这个问题。清除模拟器缓存后,问题得到了解决。

enter image description here


1
这个方法对我也起作用了,感谢您发布解决方案,同时也感谢谷歌提供如此惊人的浪费时间错误描述。 - MBH

15

在我遇到的情况中,问题出在手机日期上。请检查它,并将其设置为自动。


14

我的日期和时间是正确的,但是我没有在系统设置中勾选“使用网络提供的时间”。

通过进入“设置”->“日期和时间”->勾选“使用网络提供的时间”和“使用网络提供的时区”,我解决了这个问题。

然后这个错误就消失了。


在 OnePlus 8 上,两者都被检查了,但错误仍然发生。 - 3c71
解决方案适用于Android模拟器。 - Rahul Mandaliya

10
public static void trustEveryone() {
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }});
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new X509TrustManager[]{new 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[0];
                }}}, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(
                    context.getSocketFactory());
        } catch (Exception e) { // should never happen
            e.printStackTrace();
        }
    }

或者检查您设备的系统日期 - 当我尝试使用错误的日期进行连接时,我遇到了这个异常!


我尝试使用这样的代码发布更新,但由于安全原因,Google 阻止了发布。 - Vadim

7
如果有人遇到特定设备的这个问题,那么原因应该是设备中设置的日期不正确。

6
我通过重置模拟器的日期和时间来解决了这个错误。我的服务器正常工作,只是我将模拟器的日期和时间更改为当前服务器所在的时区。

2
如果您使用Android模拟器,您可以清除数据并重新运行,这将有效。

这对我有用,在清除我的数据之后。 - Onalo Joseph

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接