78

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;
    }
Keselme
  • 3,779
  • 7
  • 36
  • 68

12 Answers12

207

In my case it was wrong date on the phone.

Fixing the date resolved an issue

Vadim
  • 3,855
  • 2
  • 17
  • 22
  • 1
    I got the same issue with an android tv emulator. Updating the date and setting the right time zone solved the problem. – Loïc Dumas Mar 16 '21 at 14:49
  • 1
    This was the solution for me. I just set date to "automatic" and it worked. But is there a way to make it work with "manual" date settings? – Krishnom May 12 '21 at 01:42
  • 1
    @Krishnom, should work if you manually set right time – Vadim May 17 '21 at 06:07
  • 3
    The reason of problem on Android 12 emulator was the same. Cold boot of emulator worked for me. – Eugene Babich May 10 '22 at 06:55
  • 13/09/2022 - I noticed that every time I start the same emulator, its date is always set to the day before, make sure to verify this. – Pedro Massango Sep 13 '22 at 10:48
  • I also had this same issue for a number of phones and realised that the date was off on all of them. Changing it to automatic fixed the issue. – John Spax May 15 '23 at 12:22
45

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.

33

The problem was that the certificate was expired.

Keselme
  • 3,779
  • 7
  • 36
  • 68
32

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

enter image description here

Md Imran Choudhury
  • 9,343
  • 4
  • 62
  • 60
  • 1
    This worked for me too, thank you for posting your solution, and thanks for google for giving such an amazing waste of time error description – MBH Feb 23 '23 at 14:23
14

In my case, the issue was with the phone date. So please check it, set to automatic.

Hayk Mkrtchyan
  • 2,835
  • 3
  • 19
  • 61
13

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.

zetatlas
  • 320
  • 2
  • 8
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();
        }
    }

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

Pavlo Synytsia
  • 101
  • 1
  • 3
  • I tried release an update with such code and release was blocked by Google by security reasons. – Vadim Aug 01 '19 at 08:04
7

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

6

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.

2

If you use android emulator, you can wipe data and run again, it works

1

@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'
Emir Vildanov
  • 71
  • 2
  • 3
0

In my case the date/ time was ok and I was still getting the exception. I restarted my device and the problem went away. Hope it helps someone if all the above fails.

android enthusiast
  • 2,062
  • 2
  • 24
  • 45