gpt4 book ai didi

android - 如何在 Interceptor Android 中获取 401 状态代码时更改 Activity

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:10:40 25 4
gpt4 key购买 nike

当我在 API 中收到 401 状态代码 时,我必须打开登录 Activity 。我不想将更改 Activity 逻辑放在每个 API 的 onError 方法中。我想要一个用于所有 API 的全局方法。所以为此,我创建了一个拦截器

public class MyInterceptor extends BaseActivity implements Interceptor {

@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());

if (response.code() == 401) {

throw new RuntimeException(" Here you got 401 from API !");
}

return response;
}
}

这里我添加这个拦截器

OkHttpClient.Builder builder=new OkHttpClient.Builder()
.addNetworkInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Content-Type", "application/json")
.addHeader("User-Agent", "MyApp-Android-App")
.build();
return chain.proceed(newRequest);
}
})
.addNetworkInterceptor(new StethoInterceptor())
.addNetworkInterceptor(new MyInterceptor())
.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));

现在,我应该在哪里添加更改 Activity 调用方法。我使用 RxRetrofit 调用 API 的另一件事。我想要一个全局方法来处理这个 401 响应。你能给我提供任何解决方案吗?我应该在哪里调用 Activity 更改方法?

最佳答案

创建拦截器类

class HeaderInterceptor implements Interceptor
{
@Override
public Response intercept(Chain chain) throws IOException {
Request orignal = chain.request();
///--------------------------
String token="your auth token"; //retriving depend upon you
//---------------------------

Request request =orignal.newBuilder().header("Authorization", "Bearer "+ token)
.header("Accept", "application/json")
.header("Content-Type", "application/json").
method(orignal.method(), orignal.body())
.build();

Response response = chain.proceed(request);
Log.d("MyApp", "Code : "+response.code());
if (response.code() == 401){
//handle it as per ur need
return response;
}
return response;
}
}

现在添加拦截器

.....
.addInterceptor(logging).addInterceptor(new HeaderInterceptor())
.build();
..

关于android - 如何在 Interceptor Android 中获取 401 状态代码时更改 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43802715/

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