添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

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 5, 2018 at 21:32 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 5, 2018 at 21:49 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 – msrd0 Jan 5, 2018 at 23:00

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()

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
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.