Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, HttpURLConnection and handling bad credentials

I'm performing a GET request:

HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setConnectTimeout(CONNECT_TIMEOUT);
urlConnection.setReadTimeout(READ_TIMEOUT);
urlConnection.connect();

by which time the credentials have already been set with:

Authenticator.setDefault(new Authenticator() {
  protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication(loginNameString, passwordString.toCharArray());
  }
});

Everything works fine when I supply good credentials (i.e. username and password).

What happens to the connection when bad credentials are supplied? For example, if I deliberately supply bad credentials and I call urlConnection.getResponseCode() immediately after urlConnection.connect() my app eventually times out and I have to force close. Why is that?

** Edit. So far as I can tell, the HttpURLConnection just keeps trying to connect (even with a finite timeout) when the credentials are bad. (I know this because I added the line Log.v("Authentication", "Calling..."); in my getPasswordAuthentication() method before returning). I want the connection to stop trying if it fails for bad credentials!

like image 515
SK9 Avatar asked Feb 23 '23 06:02

SK9


1 Answers

With Basic auth, the workaround is:

connection.setRequestProperty("Authorization", "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.DEFAULT));

Using android.util.Base64 package. Also note that the encodeToString() method is available since API 8 (Android 2.2).

Also, http://code.google.com/p/android/issues/detail?id=7058 is relevant.

like image 120
Pitel Avatar answered Mar 07 '23 09:03

Pitel