package com.example.kotlindemo
import android.util.Log
import okhttp3.Call
import okhttp3.Callback
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.util.concurrent.TimeUnit
object OKHttp {
private val BASE_URL = "https://jsonplaceholder.typicode.com"
val client: OkHttpClient = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build()
// 同步get请求,需要在子线程中执行,否则会阻塞主线程
fun get() {
// okhttp 网络请求
Thread(Runnable {
// 构建请求体
val request: Request = Request.Builder()
.url("$BASE_URL/posts/1")
.build()
// 构建请求对象
val call: Call = client.newCall(request)
// 发起同步请求
val response = call.execute()
// 获取返回值
val body = response.body?.string()
println(body)
}).start()
}
// 异步get请求
fun getAnsyc() {
// 构建请求体
val request: Request = Request.Builder()
.url("$BASE_URL/posts/1")
.build()
// 构建请求对象
val call: Call = client.newCall(request)
// 发起同步请求
val response = call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.e("okhttp", "get onFailure : ${e.message}")
}
override fun onResponse(call: Call, response: Response) {
if (response.isSuccessful) {
val body = response.body?.string()
Log.i("okhttp", "get success :$body")
}
}
})
}
// post 的异步请求
fun getPost() {
// 构建RequestBody
val body: FormBody = FormBody.Builder()
.add("userId", "1")
.add("id", "4")
.build()
// 构建请求体
val request: Request = Request.Builder()
.url("$BASE_URL/posts")
.post(body)
.build()
// 构建请求对象
val call: Call = client.newCall(request)
// 发起同步请求
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.e("okhttp", "post onFailure : ${e.message}")
}
override fun onResponse(call: Call, response: Response) {
if (response.isSuccessful) {
val body = response.body?.string()
Log.i("okhttp", "post success : ${body}")
}
}
})
}
}
Android --- Kotlin学习之路:Okhttp 同步异步网络请求
于 2024-07-05 16:34:14 首次发布