okhttp3的使用
原创
©著作权归作者所有:来自51CTO博客作者keyboard_sun的原创作品,请联系作者获取转载授权,否则将追究法律责任
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、运行结果
异步调用先返回值