kotlin 使用jetpack compose更改默认超时okhttp客户端

plicqrtu  于 2023-08-07  发布在  Kotlin
关注(0)|答案(1)|浏览(153)

我正在使用rapidapi.com的API。来自API提供者的响应有时很长。导致okhttp客户端上的应用程序超时。我问一下如何将okhttp的默认超时值更改为30秒

LaunchedEffect(Unit) {
        val client = OkHttpClient()

        val request = Request.Builder()
            .url("https://plantwise.p.rapidapi.com/plant/?plant_type=$plantName")
            .get()
            .addHeader("X-RapidAPI-Key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
            .addHeader("X-RapidAPI-Host", "xxxxx.rapidapi.com")
            .build()

        val response = withContext(Dispatchers.IO) {
            client.newCall(request).execute()
        }

        val responseData = response.body?.string()
        if (responseData != null) {
            plantData = gson.fromJson(responseData, PlantData::class.java)
        }

    }

字符串
我试过了,还是不行

val client = OkHttpClient.Builder()
    .connectTimeout(30, TimeUnit.SECONDS) // Set the connection timeout
    .readTimeout(30, TimeUnit.SECONDS) // Set the read timeout
    .writeTimeout(30, TimeUnit.SECONDS) // Set the write timeout
    .build()

zysjyyx4

zysjyyx41#

在没有正确应用默认超时的情况下,可以尝试直接在正在创建的Call对象上设置超时。下面是一个例子:

val call = client.newCall(request)
call.timeout().timeout(30, TimeUnit.SECONDS) // Set the timeout directly on the Call object

字符串

相关问题