Yuriy Kolbasinskiy
Yuriy Kolbasinskiy

Reputation: 3841

How to get headers from all responses using retrofit

I'm using Retrofit library version 2 with OkHttpClient.

I want to get some header from all responses.

I found one solution with OkClient:

    public class InterceptingOkClient extends OkClient{
    public InterceptingOkClient()
    {
    }

    public InterceptingOkClient(OkHttpClient client)
    {
        super(client);
    }

    @Override
    public Response execute(Request request) throws IOException
    {
        Response response = super.execute(request);

        for (Header header : response.getHeaders())
        {
            // do something with header
        }

        return response;
    }
}

But how i can do this if i'm using OkHttpClient?

Upvotes: 5

Views: 7615

Answers (2)

Charan
Charan

Reputation: 940

Yes, this is old question.. but still found to answer because myself too was searching similar one.

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

        // Request customization: add request headers
        Request.Builder requestBuilder = original.newBuilder()
                .header("Authorization", "auth-value"); // <-- this is the important line, to add new header - replaces value with same header name.

        Request request = requestBuilder.build();
        Response response = chain.proceed(request);
        Headers allHeaders = response.headers();
        String headerValue = allHeaders.get("headerName");
        return response;
    }
});

Hope, this helps!

P.S: no error handled.

Upvotes: 9

padfoot27
padfoot27

Reputation: 537

You can use the logging interceptor for that. Add it as an interceptor to your OkHttpClient builder while building the client, set the log level and voila! You will have all the information regarding the request as well as the response.

Here's how you can add the interceptor -

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpBuilder.addInterceptor(loggingInterceptor);
client = okHttpBuilder.build();

There are four options when it comes to what you want to Log - NONE,BASIC,HEADERS, and BODY.

Now build the the retrofit instance with the above defined client and you will have all the data you need.

Upvotes: -2

Related Questions