【问题标题】:HttpLoggingInterceptor not logging with retrofit 2HttpLoggingInterceptor 不使用改造 2 记录
【发布时间】:2016-05-08 21:59:11
【问题描述】:

我正在尝试使用 refrofit2、kotlin 和 logging-interceptor 记录所有请求(使用网络拦截器):

  • 改造:“2.0.2”
  • okhttp3:“3.2.0”
  • com.squareup.okhttp3:logging-interceptor 3.2.0

喜欢:

val interceptor = HttpLoggingInterceptor()
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    val okHttpClient = OkHttpClient.Builder()
        .addNetworkInterceptor(interceptor) // same for .addInterceptor(...)
        .connectTimeout(30, TimeUnit.SECONDS) //Backend is really slow
        .writeTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build()

    sRestAdapter = Retrofit.Builder()
        .client(okHttpClient)
        .baseUrl(if (host.endsWith("/")) host else "$host/")
        .addConverterFactory(GsonConverterFactory.create(gson()))
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build()

它只是打印:

D/OkHttp: --> GET url...
D/OkHttp: --> END GET

发生了什么?

--------------- 编辑--------

记录器没有显示在主线程上执行请求的错误,所以要小心。

【问题讨论】:

标签: android kotlin retrofit2


【解决方案1】:

代替

val okHttpClient = OkHttpClient.Builder()
    .addNetworkInterceptor(interceptor)
    ...

你应该有类似的东西:

val okHttpClient = OkHttpClient.Builder()
    .addInterceptor(interceptor)
    ...

addNetworkInterceptor() 使用拦截器来观察单个网络请求和响应,而addInterceptor() 添加拦截器来观察每个调用的整个跨度:从建立连接(如果有)到响应源之后已选择(源服务器、缓存或两者)。

编辑

记录器没有显示在主线程上执行请求的错误,所以要小心

在主线程上进行联网不是“普通”错误。这将导致您的应用程序被系统以NetworkOnMainThreadException 杀死,这将在拦截器有机会运行之前发生。

【讨论】:

    【解决方案2】:
    private val interceptor = run {
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.apply {
            httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        }
    }
    
    
    private val okHttpClient = OkHttpClient.Builder()
        .addNetworkInterceptor(interceptor) // same for .addInterceptor(...)
        .connectTimeout(30, TimeUnit.SECONDS) //Backend is really slow
        .writeTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build()
    

    【讨论】:

      猜你喜欢
      • 2019-12-16
      • 2018-03-02
      • 2017-04-06
      • 2017-08-07
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 2016-12-17
      • 1970-01-01
      相关资源
      最近更新 更多