我有同样的问题,但我没有找到适合自己的正确和方便的答案。
但是,我想我有一个适合您的解决方案:
您可以在对服务器发出任何请求之前使用接口 - 侦听器。
也就是说,每次您尝试发送任何授权请求时都会收到一个令牌,并且已经从发送的令牌开始工作。
例如,您想通过授权(在我的例子中是 JWT 持有者令牌)向您的服务器发送一个获取请求。
首先,我声明了一个新接口认证合约:
public interface AuthentificationContract {
interface Process{
void Auth();
void Auth(String login, String password);
}
interface Listener{
void AuthSuccess(String token);
void AuthError(String message);
}}
在哪里过程是由身份验证类实现的接口,您可以在其中向服务器发送请求以接收 JWT 令牌,并且聆听者是一个侦听器,它将根据接收令牌的结果触发主要目标类。
在 Authentication 类中,您实现 Process 接口并实现 Auth 方法以获取令牌。
public class Authentification implements AuthentificationContract.Process{
private AuthentificationContract.Listener listener;
public Authentification(AuthentificationContract.Listener _listener){
this.listener = _listener;
}
@Override
public void Auth(){
String token = //your request to get a token
//when your token arrived:
listener.AuthSuccess(token);
//else
listener.AuthError("ERROR");
}
}
重要的!!: 在构造函数中,您必须传递实现 Listener 接口的对象来触发我们的目标类(或视图).
在 View 或 Targer 类中,您应该实现接口 Listener:
public class StartAcitivity extends AppCompatActivity implements AuthentificationInterface.Listener{
private Authentification auth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_acitivity);
auth = new Authentification(this);
auth.Auth();
}
@Override
public void AuthSuccess(String token) {
//your token is here, you can do request with this token, just add it like one of headers
}
@Override
public void AuthError(String message) {
Log.d("ERROR", message);
}
}
当然,这只是一个例子,在视图中执行一些操作并不令人满意,最好使用 MVP 模式