50

I am moving from Volley to Retrofit currently version 2.0.

How to print the the full json response code ?

includes:

compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'

RestClient:

OkHttpClient client = new OkHttpClient();
        client.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Response response = chain.proceed(chain.request());                
                return response;
            }
        });


        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
                .create();


        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ROOT)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(client)
                .build();

        REST_CLIENT = retrofit.create(APIService.class);

APIService:

   @GET("my/json")
    Call<Model> getFeed();

In Activity - Calling API:

Call<Model> call = RestClient.get().getFeed();
call.enqueue(new Callback<Model>() {
    @Override
    public void onResponse(Response<Model> response, Retrofit retrofit) {

        Log.w("2.0 getFeed > response.raw() => ", response.raw().toString());//DONT WORK
        Log.w("2.0 getFeed > retrofit => ", retrofit.toString());//DONT WORK
        Log.w("2.0 getFeed > body => ", response.body().toString()); //DONT WORK
        Log.w("2.0 getFeed > getStatus => ", response.body().getStatus());

    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
        Log.e("2.0 getFeed > onFailure => ", t.toString());
    }
});
Thiago
  • 12,778
  • 14
  • 93
  • 110

12 Answers12

61

To print the full response in json:

Log.w("2.0 getFeed > Full json res wrapped in gson => ",new Gson().toJson(response));

If you'd like to have pretty print feature, use:

Log.w("2.0 getFeed > Full json res wrapped in pretty printed gson => ",new GsonBuilder().setPrettyPrinting().create().toJson(response));

Note that this prints the deserialized data (not raw response as returned from server). To get the raw response, you may use one of these:

  1. Use HttpLoggingInterceptor see: https://stackoverflow.com/a/33256827/2267723 or have your own version of interceptor
  2. Use http debugging tools such Stetho. see: http://facebook.github.io/stetho/ or Charles Web Debugging Proxy. see: https://www.charlesproxy.com
Maher Abuthraa
  • 17,493
  • 11
  • 81
  • 103
  • 1
    It's not pure response.. It just reserialize that already deserailized from response and print it. It's not the same. – HoJunLee May 14 '17 at 14:12
  • 3
    @HoJunLee, Thats true. to get raw response, user HttpLoggingInterceptor or override it. Also you can use Stetho or charles proxy to monitor HTTP trafic. – Maher Abuthraa May 23 '17 at 05:24
  • I would caution against doing this you're just adding additional overhead to convert your response object back to JSON and print it. The correct answer is to use the logging intercepter mentioned in the answer below. – Kip Diskin May 27 '17 at 03:23
  • @KipDiskin, I mentioned that in my comment and I wrote it in answer. Question was not clear about which response to have. – Maher Abuthraa Jun 02 '17 at 09:45
  • new GsonBuilder().setPrettyPrinting().create().toJson(response.body()) use this. will work fine. – Gopi Cg Nov 30 '18 at 06:21
  • Thank you so much! Saved much of my time. – hetsgandhi Mar 01 '19 at 07:31
26

Actually Square already create a class just for this, just add

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor).build();

And, in Retrofit

Retrofit retrofit = new Retrofit.Builder()
            .client(client)               
            .baseUrl("https://yourapi.com/api/")
            .build();

The interceptor class is in maven central

compile 'com.squareup.okhttp3:logging-interceptor:3.5.0'

You can set the logging level in HttpLoggingInterceptor class. BODY is the verbose one (it print everything to the Body). Further information is available on OkHttp github

Caution!

Don't forget to remove Interceptors (or change Logging Level to NONE) in production! Otherwise people will be able to see your request and response on Log Cat.

aldok
  • 17,295
  • 5
  • 53
  • 64
  • 1
    This is the correct answer. As of 5/26/17 the most recent version was 3.8.0 – Kip Diskin May 27 '17 at 03:24
  • 1
    you may handle caution via using ternary operator interceptor.setLevel(BuildConfig.DEBUG?HttpLoggingInterceptor.Level.BODY:HttpLoggingInterceptor.Level.NONE); – Mohd Qasim Aug 24 '20 at 07:05
22

Plug in the following interceptor class like this

OkHttpClient client = new OkHttpClient();
        client.interceptors().add(new LoggingInterceptor());

//////Interceptor class

public static class LoggingInterceptor implements Interceptor {
        @Override
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            Log.i("LoggingInterceptor","inside intercept callback");
            Request request = chain.request();
            long t1 = System.nanoTime();
            String requestLog = String.format("Sending request %s on %s%n%s",
                    request.url(), chain.connection(), request.headers());
            if(request.method().compareToIgnoreCase("post")==0){
                requestLog ="\n"+requestLog+"\n"+bodyToString(request);
            }
            Log.d("TAG","request"+"\n"+requestLog);
            com.squareup.okhttp.Response response = chain.proceed(request);
            long t2 = System.nanoTime();

            String responseLog = String.format("Received response for %s in %.1fms%n%s",
                    response.request().url(), (t2 - t1) / 1e6d, response.headers());

            String bodyString = response.body().string();

            Log.d("TAG","response only"+"\n"+bodyString);

            Log.d("TAG","response"+"\n"+responseLog+"\n"+bodyString);

            return response.newBuilder()
                    .body(ResponseBody.create(response.body().contentType(), bodyString))
                    .build();

        }


public static String bodyToString(final Request request) {
    try {
        final Request copy = request.newBuilder().build();
        final Buffer buffer = new Buffer();
        copy.body().writeTo(buffer);
        return buffer.readUtf8();
    } catch (final IOException e) {
        return "did not work";
    }
}`

Courtesy: https://github.com/square/retrofit/issues/1072#

DGN
  • 702
  • 3
  • 12
  • It works for me, thanks . Nevertheless it is enough to add only following part of code `Response response = chain.proceed(request); ... Log.d("TAG","response"+"\n"+resposneLog+"\n"+bodyString);` into your *new Interceptor() {...}* – murt Apr 28 '16 at 13:38
  • 1
    this works great for me, very good for logging independently all network responses outside my application logics. – frey Nov 26 '16 at 15:31
  • With using `response.peekBody()` method, there's no need to create a new `ResponseBody` – a.l. Nov 03 '17 at 08:27
8

To get full response in Json in retrofit use below.

this works for me.

call.enqueue(new Callback<someList>() {
        @Override
        public void onResponse(Call<someList> call, Response<someList> response) {
            if (response.isSuccessful())
                Log.e("Success", new Gson().toJson(response.body()));
            else
                Log.e("unSuccess", new Gson().toJson(response.errorBody()));
        }

        @Override
        public void onFailure(Call<someList> call, Throwable t) {
            Log.e("onFailure", t.toString());
        }
    });
Dhiren Basra
  • 820
  • 9
  • 24
4

You can setLogLevel to your Retrofit adapter like below, and see the response and other data such as header, response code vs.

setLogLevel(LogLevel.FULL)

If you're using Retrofit version 2+ you have to set OkHttpLoggingInterceptor to see logs.

First add OkHttpLoggingInterceptor to your project:

com.squareup.okhttp3:logging-interceptor:${Versions.okHttpLoggingInterceptorVersion}

And than create init your interceptor:

HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }

And finally add it to your OkHttpClient

with(OkHttpClient.Builder()) {
            if (BuildConfig.DEBUG) addInterceptor(loggingInterceptor)
            build()
        }
savepopulation
  • 11,736
  • 4
  • 55
  • 80
3

Try this !!

 Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    /** Handles Log */
    retrofit.client().interceptors().add(new LoggingInterceptor());

    mRestClient = retrofit.create(RestServices.class);





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

    long t1 = System.nanoTime();
    Logger.d(String.format("Sending request %s on %s%n%s",
            request.url(), chain.connection(), request.headers()));

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    Logger.d(String.format("Received response for %s in %.1fms%n%s",
            response.request().url(), (t2 - t1) / 1e6d, response.headers()));


    final String responseString = new String(response.body().bytes());

    Logger.d("Response: " + responseString);

    return  response.newBuilder()
            .body(ResponseBody.create(response.body().contentType(), responseString))
            .build();
}

Check this Demo !!!

sreekumar
  • 2,439
  • 1
  • 21
  • 27
2
Log.e("TAG","2.0 getFeed > response.raw() => " +  new Gson().toJson(response.body()));
1
public class HttpLoggingInterceptor {
    HttpLoggingInterceptor provideHttpLoggingInterceptor(){
        return new HttpLoggingInterceptor(message ->
                Log.d("TAG", message)).setLevel(HttpLoggingInterceptor.Level.BODY);
    }
}


public class OkHttpClient {
    OkHttpClient provideOkHttpClient(@NonNull HttpLoggingInterceptor interceptor){
        return new OkHttpClient.Builder()
               .addInterceptor(interceptor)
               .build();
    }  
}
1

To get full json response with retrofit 2.0 follow code given below

Api Interface

@GET("my/json")
    Call<JsonObject> getFeed();

Retrofit Call function

Call<JsonObject> call = RestClient.get().getFeed();
    call.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            Log.d("res", response.body().toString());
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            Log.d("error",t.getMessage());
        }
    });
Abdul Hanan
  • 93
  • 1
  • 7
0

Try this :

 Log.d("LOG","RESPONSE ==="+response.raw().toString());
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71
0

Take a look on okhttp3.logging package, they already have HttpLoggingInterceptor that you can use for your needs. And depending on them you can also specify logging level.

and you can include this interceptor to your request as mentioned - via OkHttpClient.Builder:

public OkHttpClient provideOkHttpClient() {
    final OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
    okHttpBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
    return okHttpBuilder.build();
}
Anton Kogan
  • 153
  • 2
  • 10
-1
Call<Model> call = RestClient.get().getFeed();call.enqueue(new Callbstrong




textack<Model>() {

@Override


public void onResponse(Response<Model> response, Retrofit retrofit) {


//try this 


Call<Model> call = response.body();

//  this is enough for retrieve model


}

@Override
public void onFailure(Throwable t) {

  t.printStackTrace();

        og.e("2.0 getFeed > onFailure => ", t.toString());

}

});
Mosam Mehta
  • 1,658
  • 6
  • 25
  • 34