サーバーからの認証が必要なアプリケーションがあります。そのサーバーからサービスを取得しようとするたびに、Authenticator クラスを拡張したクラスを使用して、このコード行を設定する必要があります。
Authenticator.setDefault(new UserAuthenticator("my_mail", "my_password"));
これは UserAuthenticator クラスです:
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import android.util.Log;
public class UserAuthenticator extends Authenticator
{
//counter used to iterate login process
private int redirect;
private String email;
private String password;
/**
* UserAuthenticator constructor
*/
public UserAuthenticator(String mail, String pwd)
{
this.email = mail;
this.password = pwd;
Log.d("email+password", email+password);
}
/**
* <p>Called when password authorization is needed</p>
*
*/
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
//to catch login redirect exception
if(redirect>0){
return null;
}else{
redirect ++;
}
/**
* <p>Return the information (a data holder that is used by
* Authenticator</p
*/
return new PasswordAuthentication(email,
password.toCharArray());
}
public PasswordAuthentication authenticationResult()
{
return getPasswordAuthentication();
}
}
このクラスを一度だけインスタンス化して、残りのすべてのアクティビティで使用する方法はありますか (ユーザーは認証されたままになります)。
つまり、ユーザーを一度認証し、サーバーに要求する必要があるたびにそのクラスのインスタンス化を繰り返さないようにしたいということです。
ps: 静的内部クラスにしようとしましたが、毎回インスタンス化しないと機能しません。私はこのクラスをJava Webアプリケーションで知っていたので、AuthenticatorクラスではなくAndroidに別の方法があるかもしれません。