简单举例okhttp发送post请求。
比如说发送post请求,API的地址是https://www.abc.com/api/test,参数是username。
首先引用包名
import okhttp3.*
import okhttp3.RequestBody.Companion.toRequestBody
构建post参数和请求
val urlAPI: String = "https://www.abc.com/api/test"
val builder = FormBody.Builder()
builder.add("username", "彭裤子")
val formBody = builder.build()
val request = Request.Builder()
.method("POST", formBody)
.url(urlAPI).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
val result = response.body?.string()
println("result:" + result)
}
override fun onFailure(call: Call, e: IOException) {
println("Failed request api :( " + e.message)
}
})