2

私のアプリは、それぞれが独自のユーザー名とパスワードのペアを持つ複数のサーバーに接続する必要があります。ただし、Androidのjavadocで提供されている例では、ユーザー名/パスワードのセットが異なる複数のホストは考慮されていません。


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

これにより、VM全体の認証ハンドラーが設定され、接続しようとしているホストを特定する方法がありません。HttpUrlConenctionを使用して、さまざまなホストのさまざまなユーザー/パスでHTTP認証を処理する方法はありますか?

4

1 に答える 1

3

AuthenticatorのgetRequestingHost()メソッドを使用します。

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;
    });
})
于 2012-12-04T18:11:18.993 に答える