Tuesday, July 24, 2018

HttpURLConnection throws java.net.SocketTimeoutException: SSL handshake timed out in Android 4.1.1

My code works fine when it is run in Android 5.0 and up. But in Android 4.1.1 it throws java.net.SocketTimeoutException: SSL handshake timed out.



    URL url;
HttpURLConnection connection = null;

String charset = "UTF-8";

String accessToken = "";

try {

ArrayList postParameters = new ArrayList();
postParameters.add(new BasicNameValuePair("client_id", CLIENT_ID));
postParameters.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
postParameters.add(new BasicNameValuePair("grant_type", CLIENT_CREDENTIALS_GRANT_TYPE));


//Create connection
url = new URL(ACCESS_TOKEN_URL);
connection = (HttpURLConnection)url.openConnection();
connection.setReadTimeout( 10000 /*milliseconds*/ );
connection.setConnectTimeout( 15000 /* milliseconds */ );
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
connection.setUseCaches(false);

connection.setDoInput(true);
connection.setDoOutput(true);

//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(getQuery(postParameters).getBytes(charset));
wr.flush();
wr.close();

int responseCode = connection.getResponseCode();

InputStream is = null;

if(responseCode==HttpStatus.SC_OK) {
is = connection.getInputStream();
}
else{
is = connection.getErrorStream();
}

Log.d(TAG, "responseCode: "+responseCode);


BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;

while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}

is.close();

reader.close();

String jsonResult = sb.toString();
JSONObject jsonObject = new JSONObject(jsonResult);

if(responseCode==HttpStatus.SC_OK){
accessToken = jsonObject.getString("access_token");
SettingsPreference.setAccessToken(accessToken);
Log.d(TAG, "access token: "+accessToken);
}

else {
accessToken = null;
}

} catch (Exception e) {
e.printStackTrace();
} finally {

if(connection != null) {
connection.disconnect();

}
}


I already done a lot of research and it is quite frustrating. What did I go wrong? Is this a server issue? Your help is greatly appreciated.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...