Java 改造 2.0 如何打印完整的 json 响应?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32965790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:05:42  来源:igfitidea点击:

retrofit 2.0 how to print the full json response?

javaandroidhttpandroid-activityretrofit

提问by Joolah

I am moving from Volley to Retrofit currently version 2.0.

我正在从 Volley 转向 Retrofit 当前版本 2.0。

How to print the the full json response code ?

如何打印完整的 json 响应代码?

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:

API服务

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

In Activity - Calling API:

在活动中 - 调用 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());
    }
});

回答by savepopulation

You can setLogLevelto your Retrofitadapter like below, and see the response and other data such as header, response code vs.

您可以像下面那样setLogLevel访问您的Retrofit适配器,并查看响应和其他数据,例如标头、响应代码与响应。

setLogLevel(LogLevel.FULL)

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

如果您使用的是 Retrofit 版本 2+,则必须设置OkHttpLoggingInterceptor为查看日志。

First add OkHttpLoggingInterceptorto your project:

首先添加OkHttpLoggingInterceptor到您的项目中:

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

And than create init your interceptor:

然后创建 init 你的拦截器:

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

And finally add it to your OkHttpClient

最后将其添加到您的 OkHttpClient

with(OkHttpClient.Builder()) {
            if (BuildConfig.DEBUG) addInterceptor(loggingInterceptor)
            build()
        }

回答by DGN

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#

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

回答by sreekumar

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

检查这个演示!!!

回答by user3551205

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

}

});

回答by Maher Abuthraa

To print the full response in json:

要在 json 中打印完整的响应:

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

If you'd like to have pretty printfeature, 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 HttpLoggingInterceptorsee: https://stackoverflow.com/a/33256827/2267723or 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
  1. 使用HttpLoggingInterceptor请参见:https: //stackoverflow.com/a/33256827/2267723或拥有自己的拦截器版本
  2. 使用 http 调试工具,例如Stetho. 请参阅:http: //facebook.github.io/stetho/Charles Web Debugging Proxy。见:https: //www.charlesproxy.com

回答by aldok

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

实际上 Square 已经为此创建了一个类,只需添加

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

拦截器类位于 maven 中心

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

您可以在 HttpLoggingInterceptor 类中设置日志记录级别。BODY 是冗长的(它将所有内容打印到 Body)。更多信息可在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.

不要忘记在生产中删除拦截器(或将日志级别更改为无)!否则人们将能够在 Log Cat 上看到您的请求和响应。

回答by Dhiren

To get full response in Json in retrofit2.3.0 use below.

要在下面的retrofit2.3.0 中使用Json 获得完整响应。

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

回答by Saurabh Mistry

Try this :

尝试这个 :

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

回答by Anton Kogan

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.

看看 okhttp3.logging 包,他们已经有 HttpLoggingInterceptor 可以满足您的需求。根据它们,您还可以指定日志记录级别。

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

并且您可以将这个拦截器包含在您的请求中 - 通过 OkHttpClient.Builder:

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

回答by Антон Лялин

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