Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 671
Morteza Rastgoo Avatar asked Aug 25 '15 05:08

Morteza Rastgoo


People also ask

How do I add a header to an OkHttp request?

Adds a header with name and value. Prefer this method for multiply-valued headers like "Cookie". Note that for some headers including Content-Length and Content-Encoding, OkHttp may replace value with a header derived from the request body.

What is header in OkHttp?

The header fields of a single HTTP message. Values are uninterpreted strings; use Request and Response for interpreted headers. This class maintains the order of the header fields within the HTTP message. This class tracks header values line-by-line.

What is interceptor in OkHttp?

Interceptors, according to the documentation, are a powerful mechanism that can monitor, rewrite, and retry the API call. So, when we make an API call, we can either monitor it or perform some tasks. In a nutshell, Interceptors function similarly to airport security personnel during the security check process.

How do I add an interceptor to Okhttpclient?

header("User-Agent", "OkHttp Headers. java") . addHeader("Accept", "application/json; q=0.5") . addHeader("Accept", "application/vnd.


3 Answers

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);
    }
like image 107
Morteza Rastgoo Avatar answered Oct 20 '22 13:10

Morteza Rastgoo


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();
    }
like image 34
gaurang Avatar answered Oct 20 '22 12:10

gaurang


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();
like image 26
chebaby Avatar answered Oct 20 '22 12:10

chebaby