使用Retrofit 2进行记录 [英] Logging with Retrofit 2

查看:203
本文介绍了使用Retrofit 2进行记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取请求中发送的确切JSON。这是我的代码:

I'm trying to get the exact JSON that is being sent in the request. Here is my code:

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor(){
   @Override public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
      Request request = chain.request();
      Log.e(String.format("\nrequest:\n%s\nheaders:\n%s",
                          request.body().toString(), request.headers()));
      com.squareup.okhttp.Response response = chain.proceed(request);
      return response;
   }
});
Retrofit retrofit = new Retrofit.Builder()
   .baseUrl(API_URL)
   .addConverterFactory(GsonConverterFactory.create())
   .client(client).build();

但我只在日志中看到这一点:

But I only see this in the logs:

request:
com.squareup.okhttp.RequestBody$1@3ff4074d
headers:
Content-Type: application/vnd.ll.event.list+json

如果删除 setLog()和 setLogLevel()我们曾经使用过Retrofit 1?

How am I supposed to do proper logging, given the removal of setLog() and setLogLevel() which we used to use with Retrofit 1?

推荐答案

在Retrofit 2中你应该使用 HttpLoggingInterceptor

In Retrofit 2 you should use HttpLoggingInterceptor.

将依赖项添加到 build.gradle

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

创建一个 Retrofit 对象,如下所示:

Create a Retrofit object like the following:

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

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://backend.example.com")
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

return retrofit.create(ApiClient.class);

以上解决方案为您提供与

The above solution gives you logcat messages very similar to the old ones set by

setLogLevel(RestAdapter.LogLevel.FULL)

如果 java.lang.ClassNotFoundException

In case of java.lang.ClassNotFoundException:

旧版改造版可能需要较旧的 logging-interceptor 版本。有关详细信息,请查看注释部分。

Older Retrofit version might require an older logging-interceptor version. Take a look at comments sections for details.

这篇关于使用Retrofit 2进行记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆