我正在使用Retrofit2向服务器发出请求。
问题是:有时服务器会针对用户的每个请求返回代码401。如果用户获得此代码,则应立即将他从应用中踢出(注销,并且在重新登录之前不能执行任何操作)。
因此,对于发送到服务器的每个请求,我想检查服务器是否响应此代码。在所有请求调用中写这张支票并不是一件很漂亮的事,所以我只想写这张支票,它会在用户每次发出请求时执行!
改造(当前版本)需要HTTP客户端进行请求。由同一开发人员提供的OkHttp库与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。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句