我试图获得在请求中发送的确切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
我应该如何做正确的日志记录,给定的删除setLog()和setLogLevel(),我们用来使用的Retrofit 1?
如果您正在使用Retrofit2和okhttp3,那么您需要知道Interceptor是通过队列工作的。所以在你的其他interceptor之后添加loggingInterceptor:
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
if (BuildConfig.DEBUG)
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.addInterceptor(new CatalogInterceptor(context))//first
.addInterceptor(new OAuthInterceptor(context))//second
.authenticator(new BearerTokenAuthenticator(context))
.addInterceptor(loggingInterceptor)//third, log at the end
.build();
在Retrofit 2中做到这一点的最好方法是添加记录器拦截器作为networkInterceptor,这将打印出网络头和您的自定义头。重要的是要记住,拦截器作为一个堆栈工作,并确保在所有的末尾添加记录器。
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new MyCustomInterceptor());
builder.connectTimeout(60, TimeUnit.SECONDS);
builder.readTimeout(60, TimeUnit.SECONDS);
builder.writeTimeout(60, TimeUnit.SECONDS);
// important line here
builder.addNetworkInterceptor(LoggerInterceptor());