retrofit 2.0 how to print the full json response?

JavaAndroidHttpAndroid ActivityRetrofit

Java Problem Overview


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());
    }
});

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Solution 3 - Java

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#

Solution 4 - Java

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());
        }
    });

Solution 5 - Java

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()
        }

Solution 6 - Java

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 !!!

Solution 7 - Java

Log.e("TAG","2.0 getFeed > response.raw() => " +  new Gson().toJson(response.body()));

Solution 8 - Java

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();
    }  
}

Solution 9 - Java

Try this :

 Log.d("LOG","RESPONSE ==="+response.raw().toString());

Solution 10 - Java

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();
}

Solution 11 - Java

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());
        }
    });

Solution 12 - Java

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());

}

});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThiagoView Question on Stackoverflow
Solution 1 - JavaMaher AbuthraaView Answer on Stackoverflow
Solution 2 - JavaaldokView Answer on Stackoverflow
Solution 3 - JavaDGNView Answer on Stackoverflow
Solution 4 - JavaDhirenView Answer on Stackoverflow
Solution 5 - JavasavepopulationView Answer on Stackoverflow
Solution 6 - JavasreekumarView Answer on Stackoverflow
Solution 7 - JavaManav IsaraniView Answer on Stackoverflow
Solution 8 - JavaАнтон ЛялинView Answer on Stackoverflow
Solution 9 - JavaSaurabh MistryView Answer on Stackoverflow
Solution 10 - JavaAnton KoganView Answer on Stackoverflow
Solution 11 - JavaAbdul HananView Answer on Stackoverflow
Solution 12 - JavaUsername SathishView Answer on Stackoverflow