Android: HttpsUrlConnection with Authenticator for Basic Authentication iterates forever when password is wrong (on 401 response)

后端 未结 2 803
再見小時候
再見小時候 2020-12-31 10:46

I am using an HttpsUrlConnection with Basic Authentication by using an Authenticator and setting a default Authenticator object like t

相关标签:
2条回答
  • 2020-12-31 11:07

    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.

    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(loginUrl);
    String authString = (userName+":"+password);
    get.addHeader("Authorization", "Basic " + 
        Base64.encodeToString(authString.getBytes(),Base64.NO_WRAP));
    HttpResponse response = client.execute(get);
    
    BufferedReader r = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    
    0 讨论(0)
  • 2020-12-31 11:12

    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)

    public class MyRequest
    {
        private boolean alreadyTriedAuthenticating = false;
        private URL url;
    
        ...
    
        public void send()
        {
            HttpUrlConnection connection = (HttpUrlConnection) url.openConnection();
            Authenticator.setDefault(new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    if (!alreadyTriedAuthenticating)
                    {
                        alreadyTriedAuthenticating = true;
                        return new PasswordAuthentication(username, password.toCharArray());
                    }
                    else
                    {
                        return null;
                    }
                }
                InputStream in = new BufferedInputStream(connection.getInputStream());
    
                ...
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题