Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTPS request hangs only on Android APIs below 20 even with a connect timeout set

Tags:

java

android

I made a java.net.HttpURLConnection and it hang on the line connection.connect() even though I’ve set a connect timeout. “b4 connect” gets logged and “after connect” never gets logged. I’ve tested on API 21 and above and things work, but I get this issue with my test on API 16-19. Here is my code below. The request is using https and the backend uses a standard nginx https configuration.

        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();

        try {
            connection.setRequestMethod("GET");
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36");
            connection.setConnectTimeout('\uea60');
            connection.setReadTimeout('\uea60');

            connection.setInstanceFollowRedirects(false);
            Log.d(TAG, "b4 connect");
            connection.connect();
            Log.d(TAG, "after connect");
            if(connection.getResponseCode() == 200) {
                return IOUtils.toString(connection.getInputStream(), "UTF-8");
            }

        } catch (Exception var) {
            throw new Exception(var.getMessage());
        } finally {
            connection.disconnect();
        }
        return null;
like image 521
user299648 Avatar asked Oct 09 '16 18:10

user299648


1 Answers

  1. You're specifying timouts using some unicode charachters. Please try regular numbers like that:

     connection.setConnectTimeout(30000);   
     сonnection.setReadTimeout(30000);
    
  2. Keep in mind "after connect" will not be logged on timeout. Exception will be thrown instead.

like image 73
Fedor Avatar answered Oct 01 '22 12:10

Fedor