我正在尝试获取在请求中发送的确切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()我们以前使用的Retrofit 1 ,我应该如何正确记录?
setLog
setLogLevel()
在Retrofit 2中,你应该使用HttpLoggingInterceptor。
将依赖项添加到build.gradle。截至2019年10月的最新版本是:
build.gradle
implementation 'com.squareup.okhttp3:logging-interceptor:4.2.1'
创建一个Retrofit如下所示的对象:
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);
如果有弃用警告,只需更改setLevel为:
interceptor.level(HttpLoggingInterceptor.Level.BODY);
上面的解决方案为你提供了与logcat消息非常相似的logcat消息
setLogLevel(RestAdapter.LogLevel.FULL)
如果是java.lang.ClassNotFoundException:
较旧的翻新版本可能需要较旧的logging-interceptor版本。查看注释部分以了解详细信息。
logging-interceptor