android - OkHttp 忽略日志记录拦截器

标签 android retrofit2 okhttp

我遇到了奇怪的问题。 OkHttp 给我这样的日志:

I/System.out: [OkHttp] sendRequest>>

I/System.out: [OkHttp] sendRequest<<

但是我在客户端初始化时声明了日志记录拦截器。

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);

OkHttpClient.Builder client = new OkHttpClient.Builder()
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .addInterceptor(chain -> {
            Request original = chain.request();
            Request.Builder builder = original.newBuilder()
                    .header("Authorization", Credentials.basic(config.login(), config.password()));
            Request request = builder.build();
            return chain.proceed(request);
        })
        .addInterceptor(httpLoggingInterceptor);

return new Retrofit.Builder()
        .baseUrl(config.getServer())
        .callbackExecutor(Executors.newSingleThreadExecutor())
        .addConverterFactory(getMoshiConverterFactory())
        .client(client.build())
        .build();

我的 gradle 包含:

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-moshi:2.3.0'
implementation 'com.squareup.moshi:moshi:1.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.7.0'
implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.7.0'

我做错了什么吗?

最佳答案

您可以将它用作网络拦截器而不是应用程序拦截器。执行 .addNetworkInterceptor(httpLoggingInterceptor); 而不是 .addInterceptor(httpLoggingInterceptor);

这可以让您“观察数据,就像数据将通过网络传输一样”。

查看更多信息in the wiki pages.

关于android - OkHttp 忽略日志记录拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51023415/

相关文章:

java - RxJava 2 & Retrofit 2 顺序独立调用

android - 向客户端请求 OkHttp 添加 cookie

android - 上传视频时出现问题 : Stream was reset: NO_ERROR

android - Jackson + Gson + Retrofit 预期为 BEGIN_OBJECT 但为 BEGIN_ARRAY

android - 在 android-billing-5.0 中获取 ProductDetails 价格

java - Android:即使应用程序从内存中清除,如何使通知可见

android - Box2D Body 不会立即移除 (LibGDX And​​roid)

android - 断言错误改造Android

Kotlin - OkHttp - 从 onResponse 返回

android - 适用于 HTC Desire 的 Android 模拟器