8

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;
user299648
  • 2,769
  • 6
  • 34
  • 43

1 Answers1

6
  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.

Fedor
  • 43,261
  • 10
  • 79
  • 89
  • Thanks for the catch, after set the timeouts to 30000 I still get the exception message "Connection closed by peer" – user299648 Oct 15 '16 at 19:14
  • @user299648 So it doesn't hang anymore as you said before? Probably that's the way it should be. – Fedor Oct 16 '16 at 03:31