0

我收到了这个错误:

Fatal Exception: kotlin.KotlinNullPointerException
com.example.manager.helper.my_api.MyServiceGenerator$createService$$inlined$-addInterceptor$1.intercept (Interceptor.kt:81)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:100)
okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp (RealCall.kt:197)
okhttp3.internal.connection.RealCall$AsyncCall.run (RealCall.kt:502)
java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1133)
java.lang.Thread.run (Thread.java:762)

我不知道它为什么会引起。

我实施的是:

        val logging = HttpLoggingInterceptor()

        if (BuildConfig.DEBUG) { // If Build is Debug Mode, Show Log
            logging.level = HttpLoggingInterceptor.Level.BODY // Logs request and response lines and their respective headers and bodies (if present).
        } else { // Otherwise, show nothing.
            logging.level = HttpLoggingInterceptor.Level.NONE // No logs
        }

        val client = OkHttpClient.Builder()
        client.addInterceptor {
            val original = it.request()

            val request = original.newBuilder()
                    .header("User-Agent", MyApp.httpUserAgent!!)
                    .build()

            it.proceed(request)
        }

        client.addInterceptor(logging)
                .connectTimeout(30, TimeUnit.SECONDS)
                .callTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
4

3 回答 3

0

将日志拦截器从 3.10.0 升级到 4.7.2 时我遇到了同样的问题

调试发现原因是 ssl 工厂

// old code
builder.sslSocketFactory(sslSocketFactory)

将代码更改为新代码

// new code
builder.sslSocketFactory(sslSocketFactory, x509TrustManager)
于 2021-11-30T06:54:52.063 回答
0

您还没有完成客户端的构建。这就是为什么它是空的。一般来说,您忘记调用 build() 方法。

这就是它必须执行的方式。

    val client = OkHttpClient.Builder()
            .addInterceptor(logging)
            .connectTimeout(30, TimeUnit.SECONDS)
            .callTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build()
于 2020-04-27T13:18:15.597 回答
0

如果您!!在代码中使用,则应将其与空检查一起使用。像这样

if(MyApp.httpUserAgent != null) {
    val request = original.newBuilder()
                          .header("User-Agent", MyApp.httpUserAgent!!)
                          .build()
else {
    //here do something in case of null
}
于 2020-04-27T15:56:17.703 回答