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.