HTTP Authentication for HttpURLConnection in Android
-
28-03-2021 - |
Frage
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?
Lösung
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;
});
})
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow