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; }
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. In my case, I fetch this issue on Android Emulator. When I clear emulator cache has resolved the issue.
It is simply a list of certificates that are related to each other because they were issued within the same CA hierarchy. In order for any certificate to be validated, all of the certificates in its chain have to be validated.
In my case it was wrong date on phone.
Fixing date resolved an issue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With