我正在使用retrofit 2.x,我想记录请求和响应的标题和正文。
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.addNetworkInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("key", "value")
.addHeader("HEADER","HEADER Value")
.build();
return chain.proceed(request);
}
}).build();
这就是我正在做的,我的问题是请求的标题没有记录在Android监视器,但休息一切都记录下来。
Gradle版本
compile ('com.squareup.retrofit2:retrofit:2.0.0-beta3') {
// exclude Retrofit’s OkHttp peer-dependency module and define your own module import
exclude module: 'okhttp'
}
compile 'com.squareup.okhttp3:okhttp:3.0.0-RC1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta3'
compile ('com.squareup.okhttp3:logging-interceptor:3.0.1'){
exclude module: 'okhttp'
}
由于bug报告Bug Link使用RC1和3.0.1
哦,如果有人有兴趣,我发现错误:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("key", "value")
.addHeader("HEADER","HEADER Value")
.build();
return chain.proceed(request);
}
}).build();
您必须在请求拦截器之后添加日志拦截器(您的拦截器变量),因此正确的答案是:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws
IOException {
Request request = chain.request().newBuilder()
.addHeader("key", "value")
.addHeader("HEADER","HEADER Value")
.build();
return chain.proceed(request);
}
})
.addInterceptor(interceptor)
.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.build();
可以帮助别人......
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
添加两个以查看完整日志并在最后添加此拦截器(不知道为什么,但它像这样)。
不使用addInterceptor
添加日志记录拦截器,而是使用addNetworkInterceptor
来包含由OkHttp添加的标头。
观察数据,就像它将通过网络传输一样。
您需要设置以下内容:
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
clientBuilder.addNetworkInterceptor(httpLoggingInterceptor);
clientBuilder.build()