Code_Life
Code_Life

Reputation: 5892

Retrofit 2.x : Log Header for request and response

I am using retrofit 2.x and i want to log the header and body of request and response .

  HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
            .addNetworkInterceptor(new Interceptor() {
                @Override
                public okhttp3.Response intercept(Chain chain) throws IOException {
                    Request request = chain.request().newBuilder()
                            .addHeader("key", "value")
                            .addHeader("HEADER","HEADER Value")
                            .build();
                    return chain.proceed(request);
                }


            }).build();

And this how i am doing,my problem is header of request are not being logged in Android Monitor but rest everything is logged .

Gradle Version

 compile ('com.squareup.retrofit2:retrofit:2.0.0-beta3') {
    // exclude Retrofit’s OkHttp peer-dependency module and define your own module import
    exclude module: 'okhttp'
}
compile 'com.squareup.okhttp3:okhttp:3.0.0-RC1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta3'
compile ('com.squareup.okhttp3:logging-interceptor:3.0.1'){
    exclude module: 'okhttp'
}

Using RC1 and 3.0.1 due to bug issue reported Bug Link

Upvotes: 21

Views: 12900

Answers (6)

Upendra Shah
Upendra Shah

Reputation: 2301

You need to add this lib if not added.

implementation 'com.squareup.okhttp3:logging-interceptor:4.7.2

use logger interceptor with level Body for all Log.

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

And add it to your http client. By default level is NONE. FYI

enum class Level {
    /** No logs. */
    NONE,

    /**
     * Logs request and response lines.
     *
     * Example:
     * ```
     * --> POST /greeting http/1.1 (3-byte body)
     *
     * <-- 200 OK (22ms, 6-byte body)
     * ```
     */
    BASIC,

    /**
     * Logs request and response lines and their respective headers.
     *
     * Example:
     * ```
     * --> POST /greeting http/1.1
     * Host: example.com
     * Content-Type: plain/text
     * Content-Length: 3
     * --> END POST
     *
     * <-- 200 OK (22ms)
     * Content-Type: plain/text
     * Content-Length: 6
     * <-- END HTTP
     * ```
     */
    HEADERS,

    /**
     * Logs request and response lines and their respective headers and bodies (if present).
     *
     * Example:
     * ```
     * --> POST /greeting http/1.1
     * Host: example.com
     * Content-Type: plain/text
     * Content-Length: 3
     *
     * Hi?
     * --> END POST
     *
     * <-- 200 OK (22ms)
     * Content-Type: plain/text
     * Content-Length: 6
     *
     * Hello!
     * <-- END HTTP
     * ```
     */
    BODY
  }

Upvotes: 0

Chris Sprague
Chris Sprague

Reputation: 3584

The following link was very useful: https://medium.com/swlh/okhttp-interceptors-with-retrofit-2dcc322cc3f3

OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();

//Gson Builder
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
Timber.plant(new Timber.DebugTree());

// HttpLoggingInterceptor
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(message -> Timber.i(message));
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);


/**
 * injection of interceptors to handle encryption and decryption
 */

//Encryption Interceptor
EncryptionInterceptor encryptionInterceptor = new EncryptionInterceptor(new EncryptionImpl());
//Decryption Interceptor
DecryptionInterceptor decryptionInterceptor = new DecryptionInterceptor(new DecryptionImpl());


// OkHttpClient. Be conscious with the order
OkHttpClient okHttpClient = new OkHttpClient()
    .newBuilder()
    //httpLogging interceptor for logging network requests
    .addInterceptor(httpLoggingInterceptor)
    //Encryption interceptor for encryption of request data
    .addInterceptor(encryptionInterceptor)
    // interceptor for decryption of request data
    .addInterceptor(decryptionInterceptor)
    .build();

//Retrofit
Retrofit retrofit = new Retrofit.Builder()
    .client(okHttpClient)
    .baseUrl(BASE_URL)
    // for serialization
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build();

//ApiService
apiService = retrofit.create(ApiService.class);

Upvotes: 1

Mladen Rakonjac
Mladen Rakonjac

Reputation: 9812

You need to set following:

   OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
   HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
   httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
   clientBuilder.addNetworkInterceptor(httpLoggingInterceptor);
   clientBuilder.build()

Upvotes: 3

diegoveloper
diegoveloper

Reputation: 103441

Oh I found the error if anyone is interested :

 HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(interceptor)
        .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
        .addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder()
                        .addHeader("key", "value")
                        .addHeader("HEADER","HEADER Value")
                        .build();
                return chain.proceed(request);
            }


        }).build();

You must add the log interceptor (your interceptor variable) after the request interceptor, so the correct answer is:

 HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws 
 IOException {
                Request request = chain.request().newBuilder()
                        .addHeader("key", "value")
                        .addHeader("HEADER","HEADER Value")
                        .build();
                return chain.proceed(request);
            }


        })
        .addInterceptor(interceptor)
        .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
        .build();

Upvotes: 34

Code_Life
Code_Life

Reputation: 5892

May it help someone ...

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

Add both to see complete logs and add this interceptor at the last (don't know why but its like this).

Upvotes: 12

reacuna
reacuna

Reputation: 481

Instead of using addInterceptor to add the logging interceptor, use addNetworkInterceptor, to include headers added by OkHttp.

Network interceptors are able to:

Observe the data just as it will be transmitted over the network.

Upvotes: 13

Related Questions