Android: Httpsurlconnection With Authenticator For Basic Authentication Iterates Forever When Password Is Wrong (on 401 Response)
I am using an HttpsUrlConnection with Basic Authentication by using an Authenticator and setting a default Authenticator object like this: Authenticator.setDefault(new Authenticato
Solution 1:
I solved this problem by abstracting request/response logic away into a MyRequest
class. This allows me to have a request-scoped variable that can tell my Authenticator
whether it should make a request using a specified username and password, or whether it should stop retrying (by returning null
). It looks somewhat like the following (consider this pseudocode)
publicclassMyRequest
{
privatebooleanalreadyTriedAuthenticating=false;
private URL url;
...
publicvoidsend()
{
HttpUrlConnectionconnection= (HttpUrlConnection) url.openConnection();
Authenticator.setDefault(newAuthenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
if (!alreadyTriedAuthenticating)
{
alreadyTriedAuthenticating = true;
returnnewPasswordAuthentication(username, password.toCharArray());
}
else
{
returnnull;
}
}
InputStreamin=newBufferedInputStream(connection.getInputStream());
...
}
}
Solution 2:
I wish I knew the proper answer to this, because I ran into the exact same problem. I couldn't find a way to handle the authentication error, or even get notified about it.
I ended up having to use HttpClient
instead.
HttpClientclient=newDefaultHttpClient();
HttpGetget=newHttpGet(loginUrl);
StringauthString= (userName+":"+password);
get.addHeader("Authorization", "Basic " +
Base64.encodeToString(authString.getBytes(),Base64.NO_WRAP));
HttpResponseresponse= client.execute(get);
BufferedReaderr=newBufferedReader(newInputStreamReader(response.getEntity().getContent()));
Post a Comment for "Android: Httpsurlconnection With Authenticator For Basic Authentication Iterates Forever When Password Is Wrong (on 401 Response)"