yahya
yahya

Reputation: 321

Kotlin - How to set connection timeout with OkHttp Kotlin

I see this `

How to set connection timeout with OkHttp

But this link for Java(Android) Language.I want to use kotlin Language... ` I am using OkHttp library

 val client = OkHttpClient()

 val time = client.connectTimeoutMillis() // it's get only methood but i looking for method for set Timeout

and my trouble is I cannot find how to set connection timeout and socket timeout For Kotlin.

Upvotes: 4

Views: 10298

Answers (2)

Alex Nolasco
Alex Nolasco

Reputation: 19446

Not much different than the accepted answer, but it seems it is best to return the same OkHttpClient to avoid memory leaks.

sealed class ClientBuilder {

    companion object {
        val plainClient: OkHttpClient by lazy {
             OkHttpClient
                .Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(3, TimeUnit.SECONDS)
                .writeTimeout(3, TimeUnit.SECONDS)
                .build()
        }
    }

    fun client() : OkHttpClient {
        return plainClient
    }
}

Upvotes: 0

s1m0nw1
s1m0nw1

Reputation: 81879

A Builder is required, there are no setters available. With OkHttp 3.9.1 you can do this:

val client = OkHttpClient.Builder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .writeTimeout(10, TimeUnit.SECONDS)
    .readTimeout(30, TimeUnit.SECONDS)
    .build()

Upvotes: 15

Related Questions