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

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.

This question is related to java android http-headers retrofit okhttp

The answer is


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

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!


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

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

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

  return chain.proceed(yourAuthorisedRequest);
});

and finally build your okHttpClient from this builder

OkHttpClient client = builder.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");
    }
}));

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

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

Kotlin version:

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


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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to http-headers

Set cookies for cross origin requests Adding a HTTP header to the Angular HttpClient doesn't send the header, why? Passing headers with axios POST request What is HTTP "Host" header? CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response Using Axios GET with Authorization Header in React-Native App Axios get access to response header fields Custom header to HttpClient request Send multipart/form-data files with angular using $http Best HTTP Authorization header type for JWT

Examples related to retrofit

Call another rest api from my server in Spring-Boot Retrofit 2: Get JSON from Response body Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $ Retrofit 2 - URL Query Parameter POST Multipart Form Data using Retrofit 2.0 including image How to get response as String using retrofit without using GSON or any other library in android Adding header to all request with Retrofit 2 Retrofit 2 - Dynamic URL Retrofit 2.0 how to get deserialised error response.body Logging with Retrofit 2

Examples related to okhttp

OkHttp Post Body as JSON How to add headers to OkHttp request interceptor? javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android How does OkHttp get Json string? How to set connection timeout with OkHttp Trusting all certificates with okHttp How to use OKHTTP to make a post request?