okhttp3 请求在 Kotlin 中给出 android.os.NetworkOnMainThreadException

okhttp3 request gives android.os.NetworkOnMainThreadException in Kotlin

提问人:william205 提问时间:5/7/2020 最后编辑:william205 更新时间:5/7/2020 访问量:431

问:

我正在尝试调用 API 来获取汇率。我遵循了一个教程,最终得到了以下代码:

任务:

class GetNetworkTask {

    var client = OkHttpClient()

    @Throws(IOException::class)
    fun doGetRequest(url: String) {

        val request: Request = Request.Builder().url(url).build()

        client.newCall(request).enqueue(object : Callback {

                override fun onFailure(call: Call, e: IOException) {
                    val ex = e.localizedMessage
                    Log.v("t", "Error: $ex")
                }

                override fun onResponse(call: Call, response: Response) {
                    val res: String? = response.body?.string()
                    Log.v("t", "Response: $res")
                }
            })

    }

}

叫:

private fun getRates() {

    val getNetworkTask = GetNetworkTask()

    try {
      getNetworkTask.doGetRequest("https://api.exchangeratesapi.io/latest?base=GBP")
    } catch (e: IOException) {
      e.printStackTrace()
    }

}

当我尝试运行它时,我得到了一个我不明白的问题,因为教程提到这是异步的,不应该抛出该异常。NetworkOnMainThreadException

任何修复方面的帮助将不胜感激,谢谢!

仅供参考:我对 Kotlin 和 Android 开发非常陌生,目前正在尝试为 Android 构建我的 iOS 应用程序。

更新:

日志错误:

2020-05-07 08:06:19.492 25998-25998/com.ets.toolbox E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.ets.toolbox, PID: 25998
    android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565)
        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
        at java.net.InetAddress.getAllByName(InetAddress.java:1152)
        at okhttp3.Dns$Companion$DnsSystem.lookup(Dns.kt:49)
        at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.kt:164)
        at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.kt:129)
        at okhttp3.internal.connection.RouteSelector.next(RouteSelector.kt:71)
        at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:213)
        at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:108)
        at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:76)
        at okhttp3.internal.connection.RealCall.initExchange$okhttp(RealCall.kt:245)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:32)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:82)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:197)
        at okhttp3.internal.connection.RealCall.execute(RealCall.kt:148)
        at com.ets.toolbox.ui.converters.currency.CurrencyConverterFragment.getRates(CurrencyConverterFragment.kt:294)
        at com.ets.toolbox.ui.converters.currency.CurrencyConverterFragment.onCreateView(CurrencyConverterFragment.kt:83)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
        at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2100)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1874)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1830)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
        at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Android 异步 kotlin okhttp networkonmainthread

评论


答: 暂无答案