如何向 OkHttp 请求拦截器添加报头?

我有这个拦截器,我添加到我的 OkHttp 客户端:

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);
}
}

请注意,我知道我可以添加头时,创建这样的请求:

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();

但它不适合我的需要,我需要它在拦截器里。

138595 次浏览

如果您正在使用 Revifit 库,那么您可以使用 @Header注释直接将头传递给 api 请求,而不需要使用 Interceptor。下面的例子展示了如何将头部添加到逆转适应 API 请求。

@POST(apiURL)
void methodName(
@Header(HeadersContract.HEADER_AUTHONRIZATION) String token,
@Header(HeadersContract.HEADER_CLIENT_ID) String token,
@Body TypedInput body,
Callback<String> callback);

希望能有帮助!

最后,我这样添加了标题:

@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);
}

还有一种在 OkHttp3(目前的最新版本)中添加拦截器的方法,那就是将拦截器添加到 Okhttp 构建器中

okhttpBuilder.networkInterceptors().add(chain -> {
//todo add headers etc to your AuthorisedRequest


return chain.proceed(yourAuthorisedRequest);
});

并最终从这个构建器构建您的 okHttpClient

OkHttpClient client = builder.build();

你可以这么做

private String GET(String url, Map<String, String> header) throws IOException {
Headers headerbuild = Headers.of(header);
Request request = new Request.Builder().url(url).headers(headerbuild).
build();


Response response = client.newCall(request).execute();
return response.body().string();
}

这里是一个有用的 大意Lfmingo

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();


httpClient.addInterceptor(new Interceptor() {


@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();


Request request = original.newBuilder()
.header("User-Agent", "Your-App-Name")
.header("Accept", "application/vnd.yourapi.v1.full+json")
.method(original.method(), original.body())
.build();


return chain.proceed(request);
}
}


OkHttpClient client = httpClient.build();


Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();

面对与其他样本类似的问题,这个 Kotlin 类为我工作

import okhttp3.Interceptor
import okhttp3.Response


class CustomInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain) : Response {
val request = chain.request().newBuilder()
.header("x-custom-header", "my-value")
.build()
return chain.proceed(request)
}
}
package com.example.network.interceptors;


import androidx.annotation.NonNull;


import java.io.IOException;
import java.util.Map;


import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;


public class RequestHeadersNetworkInterceptor implements Interceptor {


private final Map<String, String> headers;


public RequestHeadersNetworkInterceptor(@NonNull Map<String, String> headers) {
this.headers = headers;
}


@NonNull
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
for (Map.Entry<String, String> header : headers.entrySet()) {
if (header.getKey() == null || header.getKey().trim().isEmpty()) {
continue;
}
if (header.getValue() == null || header.getValue().trim().isEmpty()) {
builder.removeHeader(header.getKey());
} else {
builder.header(header.getKey(), header.getValue());
}
}
return chain.proceed(builder.build());
}


}

用法示例:

httpClientBuilder.networkInterceptors().add(new RequestHeadersNetworkInterceptor(new HashMap<String, String>()
{
{
put("User-Agent", getUserAgent());
put("Accept", "application/json");
}
}));
client = new OkHttpClient();


Request request = new Request.Builder().header("authorization", token).url(url).build();
MyWebSocketListener wsListener = new MyWebSocketListener(LudoRoomActivity.this);
client.newWebSocket(request, wsListener);
client.dispatcher().executorService().shutdown();

这对我很有效:

class JSONHeaderInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain) : Response {
val request = chain.request().newBuilder()
.header("Content-Type", "application/json")
.build()
return chain.proceed(request)
}
}
fun provideHttpClient(): OkHttpClient {
val okHttpClientBuilder = OkHttpClient.Builder()
okHttpClientBuilder.addInterceptor(JSONHeaderInterceptor())
return okHttpClientBuilder.build()
}

科特林版本:

fun okHttpClientFactory(): OkHttpClient {
return OkHttpClient().newBuilder()
.addInterceptor { chain ->
chain.request().newBuilder()
.addHeader(HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION)
.build()
.let(chain::proceed)
}
.build()
}


对于那些 okhttp3拦截器仍然不工作

我的拦截者:

class MyOkHttpInterceptor : Interceptor, Logging {
    

@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val mdc = MDC.getCopyOfContextMap()
var request = chain.request().newBuilder()
.header(CommonConstants.WS_USER_AGENT, CommonConstants.WS_USER_AGENT_SEARCH)
.header(CommonConstants.WS_HEADER_TRACED_ID, mdc[CommonConstants.WS_HEADER_TRACED_ID]!!)
.header(CommonConstants.WS_HEADER_ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.method(chain.request().method, chain.request().body)
.build()


return chain.proceed(request)


}
}

我的日志拦截器:

val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BASIC
  1. 我正在添加头拦截器
  2. I am adding logging interceptor
  3. 不要使用网络拦截器! ! !
val client = OkHttpClient.Builder()
.connectTimeout(httpConnectTimeOut, TimeUnit.SECONDS)
.writeTimeout(httpConnectTimeOut, TimeUnit.SECONDS)
.readTimeout(readTimeOut, TimeUnit.SECONDS)
.addInterceptor(MyOkHttpInterceptor())
.addInterceptor(interceptor)
.build()