SSLHandshakeException - Chain chain validation failed, how to solve?

AndroidHttpsSslhandshakeexception

Android Problem Overview


in my application I am trying to do a HTTPS POST request to my server. However, I keep getting SSLHandshakeException - Chain chain validation failed, all the time. I tried to send a request using POSTMAN and I got a response from the server. What can be causing this error when I try to send the request from the application?

Here a code snippet where I try to send the post request:

   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;
    }

Android Solutions


Solution 1 - Android

In my case it was wrong date on phone.

Fixing date resolved an issue

Solution 2 - Android

The problem was that the certificate was expired.

Solution 3 - Android

If you're using an emulated device it may solve the problem if you just 'Cold Boot' it.

Sometimes the date on those things can get stuck if you let them run for some time, which results in this expired-certificate-problem.

Solution 4 - Android

In my case, I fetch this issue on Android Emulator. When I clear emulator cache has resolved the issue.

enter image description here

Solution 5 - Android

My date and time were correct, but I didn't have "Use Network Provided Time checked" in my system settings.

I fixed this issue by going to Settings > Date and Time > Check "Use network-provided time" and also check "Use network-provided time zone".

Then this error went away.

Solution 6 - Android

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();
        }
    }

or check system date of your device - I had this Exception when I tried to connect with wrong date!..

Solution 7 - Android

If anyone come across this issue pertaining to specific device, then the reason should be because of incorrect date set in the device.

Solution 8 - Android

I fixed this error by resetting my emulator date and time. My server is working fine just I changed the date and time of my emulator as current server time zone.

Solution 9 - Android

@Yash Bhardwaj in the comment on @Vadim answer said that the problem was in Glide framework. I faced the same problem: Https requests to server using Ktor framework were all successful, but when Glide tried to load image from the same server, it faced the SSLHandshakeException. To solve this issue you should look here: Solve Glide SSLHandshakeException.

To make a deal with @GlideModule annotation you should import kapt plugin and add these dependencies into your app build.gradle:

implementation 'com.github.bumptech.glide:okhttp3-integration:4.11.0'
kapt 'com.github.bumptech.glide:compiler:4.12.0'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKeselmeView Question on Stackoverflow
Solution 1 - AndroidVadimView Answer on Stackoverflow
Solution 2 - AndroidKeselmeView Answer on Stackoverflow
Solution 3 - AndroidSebastian MüllerView Answer on Stackoverflow
Solution 4 - AndroidMd Imran ChoudhuryView Answer on Stackoverflow
Solution 5 - AndroidzetatlasView Answer on Stackoverflow
Solution 6 - AndroidPavlo SynytsiaView Answer on Stackoverflow
Solution 7 - Androidharishanth raveendrenView Answer on Stackoverflow
Solution 8 - AndroidSachidanand PanditView Answer on Stackoverflow
Solution 9 - AndroidEmir VildanovView Answer on Stackoverflow