[Android] Getting RAW JSON response with Retrofit2

The main thing that made me waste time when using Retrofit was that I could not see the JSON responses that my APIs were sending. I had to add a separate method to the RetrofitService that used a Response object instead of MyClass object.
This is much easier and comfortable in retrofit 2. Just add these lines:

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new LogJsonInterceptor());
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();

LogJsonInterceptor class:


public class LogJsonInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();

Response response = chain.proceed(request);
String rawJson = response.body().string();

Log.d(BuildConfig.APPLICATION_ID, String.format("raw JSON response is: %s", rawJson));

// Re-create the response before returning it because body can be read only once
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), rawJson)).build();
}
}

Here you can log your rawJson variable to display raw JSON message. Note that once body() has been called, the response has been consumed and becomes useless. You have to re-create it before returning it to another objects to consume.

Thanks to this article written by @riggaroo and this issue thread (and ofcourse uncle Jake) for making this possible.

Have a nice coding day !!! 🙂

P.D. I know that the article format is crap, but anyway you can copy and paste the code for your own purpose and it will work 😛

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s