Last Updated: February 25, 2016
·
5.088K
· rock3r

HttpURLConnection hangs on Android

As you might have noticed, sometimes on older Android versions the HttpURLConnection hangs indefinitely.

In my case, it happens on the HttpURLConnection.getResponseCode() call, under some circumstancies, most likely due to "strange" HTTP Response Headers.

The trick to get it right is to specify a valid User-Agent header. In the example, we're simulating an Android 1.6 device.

final String USER_AGENT = "Mozilla/5.0 (Linux; U; Android 1.6; en-us; GenericAndroidDevice) AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1";
HttpURLConnection urlc = (HttpURLConnection) (new java.net.URL(urlStr).openConnection());
urlc.setRequestProperty("User-Agent", USER_AGENT);
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000);
urlc.setReadTimeout(1000);
urlc.connect();

if (urlc.getResponseCode() == 200) {
    Log.d(TAG, "Connection to " + urlStr + " is AVAILABLE.");
    return true;
}
else {
    Log.d(TAG, "Connection to " + urlStr + " is NOT WORKING.");
}