I've run into what seems to be a very strange problem. I'm using the HttpsURLConnection class in my Android app, and doing authentication using the Authenticator class.
I can connect to a web service with inputted username and password, and get a JSON response back. If I enter valid credentials this works absolutely fine and I get the returned response. However if I give it invalid credentials then then I never get a response and the my Async Task (that's running the code) never completes.
The code that is doing the connection is as follows:
private static String retrieveStream(String url) throws SocketTimeoutException {
String streamContent = "";
HttpsURLConnection urlConnection = null;
try {
Log.d("Connection", "Connecting to: " + url);
Log.d("Connection", "Opening connection");
urlConnection = (HttpsURLConnection) new URL(url).openConnection();
Log.d("Connection", "Setting connect timeout");
urlConnection.setConnectTimeout(5000);
Log.d("Connection", "Setting read timeout");
urlConnection.setReadTimeout(5000);
Log.d("Connection", "Setting Allow All certs (because this is just testing)");
urlConnection.setHostnameVerifier(new AllowAllHostnameVerifier());
Log.d("Connection", "Connection Response: " + urlConnection.getResponseCode() + " " + urlConnection.getResponseMessage());
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
streamContent = readStreamFromConnection(urlConnection);
Log.d("Connection", "Returned content is: " + streamContent);
}
} catch (MalformedURLException e) {
Log.e("Error", "MalformedURLException thrown in retrieveStream: " + e);
} catch (IOException e) {
Log.e("Error", "IOException thrown in retrieveStream for " + url + " : " + e);
} finally {
urlConnection.disconnect();
}
return streamContent;
}
If I run this with invalid credentials this is what I get in the logs:
07-30 15:52:57.040: DEBUG/Connection(16000): Connecting to: https://webservice-that-i-use
07-30 15:52:57.040: DEBUG/Connection(16000): Opening connection
07-30 15:52:57.040: DEBUG/Connection(16000): Setting connect timeout
07-30 15:52:57.040: DEBUG/Connection(16000): Setting read timeout
07-30 15:52:57.040: DEBUG/Connection(16000): Setting Allow All certs (because this is just testing)
Then it just hangs here until I force stop the app or redeploy. I don't get any exceptions or ANRs.
It seems that I have the exact same problem as posted here but it was never answered. Does anyone have any ideas of why this happens? How I can get the connection to timeout on invalid credentials with HttpsURLConnection?
Any help would be appreciated. I should also note that my colleague has this working fine in iOS so it's not a server issue. This is running with the ICS SDK on a Asus Transformer TF101.
Thanks for reading!