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

12.8k views Asked by At

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<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        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.

0

There are 0 answers