1、引入maven 包

<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.9.0</version>
</dependency>

2、编写kotlin代码

import okhttp3.*
import java.io.IOException

fun getDataByGet(): Int {
try {
val client = OkHttpClient()
val request = Request.Builder().get()
.url("https://www.baidu.com")
.build()

val response = client.newCall(request)
var call = client.newCall(request)
//异步请求
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
//Log.d("UPDATE", "onFailure: $e")
println("onFailure: $e")
}

@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
//Log.d("UPDATE", "OnResponse: " + response.body()?.string())
println("{ $response.body()?.string()}")
}
})
}catch (e:Exception) {
//Log.e("UPDATE ERROR:", "", e)
}
return 1;
}

fun main(){
println(getDataByGet())
}

3、运行结果

异步调用先返回值

okhttp3的使用_kotlin