我想拦截改装引擎收到的所有回复,并扫描HTTP错误代码,例如错误403.
我知道我可以使用每个请求的失败(RetrofitError错误)回调并检查403,但我想全局包装响应。
我可以看到请求拦截是可能的,但我没有看到类似的响应选项。
有什么建议吗?
答案 0 :(得分:62)
我能够通过向改装正在使用的OkHttpClient添加一个拦截器来实现这一点。
Retrofix 2.x:
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.
addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if (response.code() == 403) {
handleForbiddenResponse();
}
return response;
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(clientBuilder.build();)
.build();
改造1.x:
public class ForbiddenInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if (response.code() == 403) {
handleForbiddenResponse();
}
return response;
}
}
OkHttpClient okHttpClient = Utils.createUnsafeOkHttpClient();
okHttpClient.interceptors().add(new ForbiddenInterceptor());
RestAdapter.Builder restAdapterBuilder = new RestAdapter.Builder()
.setEndpoint(API_BASE_URL)
.setClient(new OkClient(okHttpClient));
答案 1 :(得分:0)
另一种可能性是覆盖Retrofit execute
中的OkClient
方法。在我的情况下,我一直在寻找一个特定的响应头,所以它是这样的:
OkClient client = new OkClient(okHttpClient) {
@Override
public retrofit.client.Response execute(retrofit.client.Request request) throws IOException {
retrofit.client.Response response = super.execute(request);
// Do whatever with 'response', such as looking for the value of a particular header:
List<retrofit.client.Header> headers = response.getHeaders();
for (retrofit.client.Header header : headers) {
if (MY_HEADER.equalsIgnoreCase(header.getName())) {
this.savedValue = header.getValue();
break;
}
}
return response;
}
};
RestAdapter.Builder restAdapterBuilder = new RestAdapter.Builder()
.setEndpoint(API_BASE_URL)
.setClient(client);
答案 2 :(得分:0)
id='pass'
正如您在上面的代码段中所看到的,OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
okhttp3.Response response = chain.proceed(request);
// todo deal with the issues the way you need to
if (response.code() == 500) {
startActivity(
new Intent(
ErrorHandlingActivity.this,
ServerIsBrokenActivity.class
)
);
return response;
}
return response;
}
})
.build();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://your_url")
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
行访问服务器响应。因此,我们可以使用okhttp3.Response response = chain.proceed(request);
检查状态代码,然后打开if (response.code() == 500)
。