0

Since I need use Retrofit 2 and I have the need to Log what's happening behind the request, so the solution is add a request interceptor. I added an interceptor I take from okhttp wiki page, I also add some other changes as my needs and set it to the okhttp client at build stage but it did not work as I expected. for my surprise when I set my custom Interceptor to the okhttp client the GsonConverter is not able to parse the response json into java objects.

Here is the code from my Interceptor

public class LoggingInterceptor implements Interceptor {

private final static String TAG = "RI";

private HashMap<String, String> headersMap = null;
public LoggingInterceptor(HashMap<String, String> headers) {
    this.headersMap = headers;
}

@Override
public Response intercept(Chain chain) throws IOException {

    Request request = chain.request();
    Request.Builder reqBuilder = request.newBuilder();
    Log.e(TAG, "Headers on the map -> " + headersMap.size());
    for (String header : headersMap.keySet()) {
        reqBuilder.addHeader(header, headersMap.get(header));
    }

    request = reqBuilder.build();
    long timeRequest = System.nanoTime();
    Log.d(TAG, String.format(Locale.getDefault(), "Sending %s with %s", request.url(), request.headers()));

    Response response = chain.proceed(request);

    Log.d(TAG, "<<<=========================================>>>");
    long timeResponse = System.nanoTime();
    Log.d(TAG, String.format(Locale.getDefault(), "Receiving %s in %s%n%s", response.request().url(), ((timeResponse - timeRequest)/1e6d), response.headers()));
    Log.d(TAG, "Data: " + response.body().string());
    Log.d(TAG, "Code: " + response.code());

    return response;
}

}

And here is how I add it to the Okhttp client

private OkHttpClient createHttpClient(){
    if(client == null){

        String strUserAgent = "tm-vc=" + BuildConfig.VERSION_CODE + "-devid=" + (getDeviceID().isEmpty() ? "0" : getDeviceID());
        HashMap<String, String> headers = new HashMap<>();
        headers.put(HEADER_ACCEPT,      "application/json; charset=utf-8");
        headers.put(HEADER_USER_AGENT,  strUserAgent);
        String cookie =  getSessionCookie();
        if(cookie != null && !cookie.isEmpty())
            headers.put(HEADER_COOKIE,  cookie);
        
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new LoggingInterceptor(headers));
        builder.retryOnConnectionFailure(true);
        client = builder.build();
    }
    return client;
}

To test what I said I just need to comment this line builder.addInterceptor(new LoggingInterceptor(headers));, if you comment the line, the retrofit onResponse is called and succeded(works, json gets parsed), if not onFailure is called.

SO what do I missing on me own Interceptor implementation?

WHAT IS THE QUESTION ITSELF? How do I add headers to the request using Interceptors?

Yes, I can do with annotations but the headers's value would be static.

NOTE: Im using the totally renew Retrofit 2.

Community
  • 1
  • 1
AXSM
  • 1,142
  • 1
  • 12
  • 27

1 Answers1

1

You can use HttpLoggingInterceptor with Retrofit 2 as follows

1) Api Client

// imports
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

---

// Method to create instance of Service
public ApiService getService() {

    // Interceptor to Log the Request
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    // Level.BODY prints Urls, Params and Response
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    // Create the Client
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

    // Initialize retrofit instance
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    // Creates the instance of Web Service Representation
    return retrofit.create(ApiService.class);
}

2) Gradle dependencies

// Retrofit 2 dependency
compile 'com.squareup.retrofit2:retrofit:2.1.0'
// GSON for Parsing into POJOs
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
// Logging Interceptor to Log the  Request
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
// OK HTTP dependency (for Compatibility)
compile 'com.squareup.okhttp3:okhttp:3.4.1'

3) Likewise you can add your own customization (e.g., Headers) to Retrofit

  • your solution works but in that way I can't inject the requests headers in the request, and in this [example](https://github.com/square/okhttp/wiki/Interceptors) says it's possible. I tried to copy that sample and add some functionality but it did not work. – AXSM Sep 29 '16 at 20:49
  • Checkout this one: *[See if this could solve your issue.](http://stackoverflow.com/a/35024248/6213557) Note: Interceptors are ordered. – Rishabh Dutt Sharma Sep 29 '16 at 21:04