Question

My app needs to connect to multiple servers, each with their own username/password pairs. However The example provided in Android's javadoc does not consider multiple hosts with different sets of username/password:


 Authenticator.setDefault(new Authenticator() {
     protected PasswordAuthentication getPasswordAuthentication() {
       return new PasswordAuthentication(username, password.toCharArray());
}); }

This sets the VM-wide authentication handler, and has no way to identify which host we are trying to connect to. Is there a way that I can use HttpUrlConenction and handle HTTP Authentication with different user/passes for different hosts?

Was it helpful?

Solution

Use Authenticator's getRequestingHost() method.

Authenticator.setDefault(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        if (this.getRequestingHost() != null)
            if (this.getRequestingHost().contains("a-site.com")
                return new PasswordAuthentication(aUsername, aPassword.toCharArray());
            else if (this.getRequestingHost().contains("b-site.com")
                return new PasswordAuthentication(bUsername, bPassword.toCharArray());
        return null;
    });
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top