我正在使用 Retrofit2 向服务器发出请求。
问题是:有时服务器会为用户的每个请求返回代码401。如果用户获得此代码,他应该立即从应用程序中退出(注销并且在重新登录之前无法执行任何操作)。
因此,对于发送到服务器的每个请求,我想检查服务器是否响应此代码。在所有请求调用中写入此检查并不漂亮,因此我只想将此检查写入一个,并且每次用户发出请求时都会执行此操作!
答案 0 :(得分:2)
Retrofit(当前版本)需要HTTP客户端发出请求。同一开发人员OkHttp library与Retrofit捆绑在一起作为默认客户端。 OkHttp
支持向客户端添加Interceptor
,可以拦截请求执行。
例如:
import android.util.Log;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class ErrorInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
// before request
Request request = chain.request();
// execute request
Response response = chain.proceed(request);
// after request
// inspect status codes of unsuccessful responses
switch (response.code()){
case 401:
// do something else
Log.e("TEST","Unauthorized error for: " +request.url());
// perhaps throw a custom exception ?
throw new IOException("Unauthorized !!");
}
return response;
}
}
要使用它,请将其包含在OkHttpClient
实例使用的Retrofit
中:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new ErrorInterceptor())
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl("/")
.build();
因此,您可以为每个“全局逻辑”或“横切关注点”实现Interceptor
,并将它们全部按顺序添加到Retrofit。
答案 1 :(得分:2)
如果你需要检查“401”代码,OkHttp中有一个特殊对象:Authenticator(Recipes in OkHttp)。例如:
public class RefreshTokenAuthenticator implements Authenticator {
@Override
public Request authenticate(Route route, Response response) throws IOException {
// You get here, if response code was 401.
// Then you can somehow change your request or data in your app in this method and resend your request.
Request request = response.request();
HttpUrl url = request.url().newBuilder()
.setQueryParameter("access_token", "new_access_token_may_be")
.build();
request = request.newBuilder()
.url(url)
.build();
return request;
}
}