How to add headers to OkHttp request interceptor?(如何向 OkHttp 请求拦截器添加标头?)
问题描述
我将这个拦截器添加到我的 OkHttp 客户端:
I have this interceptor that i add to my OkHttp client:
public class RequestTokenInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// Here where we'll try to refresh token.
// with an retrofit call
// After we succeed we'll proceed our request
Response response = chain.proceed(request);
return response;
}
}
如何在拦截器中添加请求头?
How can i add headers to request in my interceptor?
我试过了,但我犯了错误,我在创建新请求时丢失了我的请求:
I tried this but i am making mistake and i lose my request when creating new request:
public class RequestTokenInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
Request newRequest;
try {
Log.d("addHeader", "Before");
String token = TokenProvider.getInstance(mContext).getToken();
newRequest = request.newBuilder()
.addHeader(HeadersContract.HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION + token)
.addHeader(HeadersContract.HEADER_CLIENT_ID, CLIENT_ID)
.build();
} catch (Exception e) {
Log.d("addHeader", "Error");
e.printStackTrace();
return chain.proceed(request);
}
Log.d("addHeader", "after");
return chain.proceed(newRequest);
}
}
请注意,我知道我可以在创建这样的请求时添加标头:
Note that, i know i can add header when creating request like this:
Request request = new Request.Builder()
.url("https://api.github.com/repos/square/okhttp/issues")
.header("User-Agent", "OkHttp Headers.java")
.addHeader("Accept", "application/json; q=0.5")
.addHeader("Accept", "application/vnd.github.v3+json")
.build();
但这不符合我的需要.我需要它在拦截器中.
But it doesn't fit my needs. I need it in interceptor.
推荐答案
最后,我是这样添加标题的:
Finally, I added the headers this way:
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
Request newRequest;
newRequest = request.newBuilder()
.addHeader(HeadersContract.HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION)
.addHeader(HeadersContract.HEADER_X_CLIENT_ID, CLIENT_ID)
.build();
return chain.proceed(newRequest);
}
这篇关于如何向 OkHttp 请求拦截器添加标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何向 OkHttp 请求拦截器添加标头?
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01