我正在尝试获取请求中发送的确切 JSON。这是我的代码:
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();
但我只在日志中看到这个:
request:
com.squareup.okhttp.RequestBody$1@3ff4074d
headers:
Content-Type: application/vnd.ll.event.list+json
鉴于删除了我们过去用于 Retrofit 1 的 setLog()
和 setLogLevel()
,我应该如何进行正确的日志记录?
原文由 Gabor 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 Retrofit 2 中,您应该使用 HttpLoggingInterceptor 。
将依赖项添加到
build.gradle
。截至 2019 年 10 月的最新版本是:创建一个
Retrofit
对象,如下所示:如果出现弃用警告,只需将
setLevel
更改为:上面的解决方案为您提供的 logcat 消息与由
在
java.lang.ClassNotFoundException
的情况下:较旧的 Retrofit 版本可能需要较旧的
logging-interceptor
版本。查看评论部分以了解详细信息。