retrofit 2.0 how to print the full json response?

2019-02-05 13:06发布

问题:

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

回答1:

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 would need to deal with HttpLoggingInterceptor or have your own version of interceptor. Other approach to use http debugging tools such as Stetho or Charles Web Debugging Proxy .



回答2:

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#



回答3:

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.



回答4:

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



回答5:

To get full response in Json in retrofit2.3.0 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());
        }
    });


回答6:

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

}

});


回答7:

Try this :

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


回答8:

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


回答9:

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


回答10:

You can set log level to your retrofit adapter like below, and see response and other data such as header, response code vs.

setLogLevel(LogLevel.FULL)

Edit: This does not work in Retrofit 2.0. If you're using 1.9 you can use.