retrofit 2.0 how to print the full json response?

时间:2015-10-06 09:00:35

标签: java android http android-activity retrofit

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

11 个答案:

答案 0 :(得分:46)

在json中打印完整的回复:

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

如果您想要漂亮的打印功能,请使用:

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

请注意,这会打印反序列化的数据(而不是从服务器返回的Raw响应)。要获得原始响应,您可以使用以下方法之一:

  1. 使用HttpLoggingInterceptor请参阅:https://stackoverflow.com/a/33256827/2267723或拥有您自己的拦截器版本
  2. 使用http Stetho等调试工具。请参阅:http://facebook.github.io/stetho/Charles Web Debugging Proxy。见:https://www.charlesproxy.com

答案 1 :(得分:18)

像这样插入以下拦截器类

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

//////拦截器类

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";
    }
}`

礼貌https://github.com/square/retrofit/issues/1072#

答案 2 :(得分:4)

要在json的retrofit2.3.0中获得完整的回复,请使用以下内容。

这适合我。

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

答案 3 :(得分:3)

试试这个!!

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

答案 4 :(得分:0)

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

答案 5 :(得分:0)

试试这个:

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

答案 6 :(得分:0)

看一下okhttp3.logging包,他们已经有了HttpLoggingInterceptor,你可以根据自己的需要使用它。 根据它们,您还可以指定日志记录级别。

你可以把这个拦截器包含在你提出的请求中 - 通过OkHttpClient.Builder:

public OkHttpClient provideOkHttpClient() {
    final OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
    okHttpBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
    return okHttpBuilder.build();
}

答案 7 :(得分:0)

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

答案 8 :(得分:0)

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

答案 9 :(得分:0)

要获得翻新版2.0的完整json响应,请遵循以下代码

Api接口

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

改造呼叫功能

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

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

}

});