How to add headers to OkHttp request interceptor?

前端 未结 10 1495
感情败类
感情败类 2020-12-01 00:24

I have this interceptor that i add to my OkHttp client:

public class RequestTokenInterceptor implements Interceptor {
@Override
public Response intercept(Cha         


        
相关标签:
10条回答
  • 2020-12-01 00:58

    here is a useful gist from 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();
    
    0 讨论(0)
  • 2020-12-01 01:07
    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();
    
    0 讨论(0)
  • 2020-12-01 01:09

    Faced similar issue with other samples, this Kotlin class worked for me

    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)
        }
    }
    
    0 讨论(0)
  • 2020-12-01 01:09

    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()
    }
    
    0 讨论(0)
  • 2020-12-01 01:11

    If you are using Retrofit library then you can directly pass header to api request using @Header annotation without use of Interceptor. Here is example that shows how to add header to Retrofit api request.

    @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!

    0 讨论(0)
  • 2020-12-01 01:12
    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");
        }
    }));
    
    0 讨论(0)
提交回复
热议问题