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.");
}
Written by Sebastiano Poggi
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Http
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#