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

二次信任 提交于 2019-11-30 08:51:39

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());

            ...

    }
}

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()));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!