gpt4 book ai didi

android - 改造 - 全局拦截响应

转载 作者:IT老高 更新时间:2023-10-28 21:57:40 25 4
gpt4 key购买 nike

我想拦截改造引擎收到的所有响应,并扫描 HTTP 错误代码,例如错误 403。

我知道我可以使用每个请求的失败(RetrofitError 错误)回调并检查 403,但我想全局包装响应。

我可以看到请求拦截是可能的,但我没有看到类似的响应选项。

有什么建议吗?

最佳答案

我能够通过向改造正在使用的 OkHttpClient 添加一个拦截器来实现这一点。

Kotlin + 改造 2.x

val clientBuilder = OkHttpClient.Builder()
clientBuilder.addInterceptor { chain ->
val request = chain.request()
val response = chain.proceed(request)
if (response.code() == 403) {
handleForbiddenResponse()
}
response
}

改造 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));

关于android - 改造 - 全局拦截响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32294557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com