简体   繁体   English

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

[英]How to add headers to OkHttp request interceptor?

I have this interceptor that i add to my OkHttp client:我有这个拦截器,我添加到我的 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);
    }
}

Note that, i know i can add header when creating request like this:请注意,我知道我可以在创建这样的请求时添加 header:

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

you can do it this way你可以这样做

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

here is a useful gist from lfmingo这是来自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();

Faced similar issue with other samples, this Kotlin class worked for me遇到与其他样本类似的问题,这个 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)
    }
}

If you are using Retrofit library then you can directly pass header to api request using @Header annotation without use of Interceptor.如果您使用的是 Retrofit 库,那么您可以使用@Header注释直接将标头传递给 api 请求,而无需使用拦截器。 Here is example that shows how to add header to Retrofit api request.这是显示如何向 Retrofit api 请求添加标头的示例。

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

Hope it helps!希望能帮助到你!

There is yet an another way to add interceptors in your OkHttp3 (latest version as of now) , that is you add the interceptors to your Okhttp builder还有另一种方法可以在 OkHttp3(截至目前的最新版本)中添加拦截器,即将拦截器添加到 Okhttp 构建器中

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

  return chain.proceed(yourAuthorisedRequest);
});

and finally build your okHttpClient from this builder最后从这个构建器构建你的 okHttpClient

OkHttpClient client = builder.build();

Kotlin version:科特林版本:

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

This worked for me:这对我有用:

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

}

Example of usage:用法示例:

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

For those to whom okhttp3 interceptor still does not work.对于那些 okhttp3 拦截器仍然不起作用的人。 Consequence of adding interceptors is make sense!添加拦截器的后果是有道理的! Kotlin example Kotlin 示例

My interceptor:我的拦截器:

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)

    }
}

My logging interceptor:我的日志拦截器:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 bytebuddy 在运行时添加 okhttp 自定义拦截器? - How to add okhttp custom interceptor at runtime using bytebuddy? 如何在 Retrofit 2.0 中使用拦截器添加标题? - How to use interceptor to add Headers in Retrofit 2.0? 编写可压缩请求正文的OkHttp拦截器 - Writing an OkHttp Interceptor that compresses request body 如何向假客户端添加请求拦截器? - How to add a request interceptor to a feign client? How to get api request and api response time in Android Retrofit api using OkHttp Interceptor for each api? - How to get api request and api response time in Android Retrofit api using OkHttp Interceptor for each api? 如何在OkHTTP拦截器中读取/更新connectTimeout和ReadTimeout? - How to read / update connectTimeout & ReadTimeout in an OkHTTP Interceptor? 如何将标头添加到已构建的OkHttp请求对象? - How to add a header to an OkHttp request object that has been built? 如何通过OkHttp将查询参数添加到HTTP GET请求? - How to add query parameters to a HTTP GET request by OkHttp? 通过拦截器或 HttpEntity 将 http 标头添加到 RestTemplate? - Add http headers to RestTemplate by Interceptor or HttpEntity? Okhttp拦截器问题 - Okhttp Interceptor issue
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM