4

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.

yahya
  • 321
  • 2
  • 16
  • Possible duplicate of [How to set connection timeout with OkHttp](https://stackoverflow.com/questions/25953819/how-to-set-connection-timeout-with-okhttp) – andrei_zaitcev Jan 05 '18 at 21:31
  • You should do the same thing. Kotlin has little difference in this aspect comparing to Java. Just call `OkHttp.Builder`, configure it with needed timeouts and build an object. The code must be the same as for Java. – andrei_zaitcev Jan 05 '18 at 21:32
  • I khow..but this link for java(android).i want for android kotlin language – yahya Jan 05 '18 at 21:33
  • val test = OkHttp.Builder.....but test not method for set timeout – yahya Jan 05 '18 at 21:35
  • 1
    The language doesn't matter in this case. Just do `val client = OkHttp.Builder().connectionTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS).build()` – andrei_zaitcev Jan 05 '18 at 21:49
  • @andrei_zaitcev I don't know to use (Builder). thank you for help. your solution works for me – yahya Jan 05 '18 at 22:03
  • 2
    The problem with the question you linked is not that it is Java and you are using Kotlin but that the accepted answer is for OkHttp2 - but [other answers are for OkHttp3](https://stackoverflow.com/a/34762061/3755692) – msrd0 Jan 05 '18 at 23:00

2 Answers2

15

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()
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
0

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
    }
}
Alex Nolasco
  • 18,750
  • 9
  • 86
  • 81