我需要从我的android项目向端点发出发布请求。我正在使用Kotlin。我是否需要为此创建一个单独的OKHttpClient类。
答案 0 :(得分:1)
这是实现此目标的方法:
val payload = "test payload"
val okHttpClient = OkHttpClient()
val requestBody = payload.toRequestBody()
val request = Request.Builder()
.method("POST", requestBody)
.url("url")
.build()
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// Handle this
}
override fun onResponse(call: Call, response: Response) {
// Handle this
}
})
别忘了导入:
import okhttp3.RequestBody.Companion.toRequestBody