我正在尝试在 Kotlin 项目中使用 OkHTTP 发出 POST 请求。但是,请求正文最终为空。
这是我尝试的代码片段:
import java.util.*
import android.os.AsyncTask
import android.util.Log
import okhttp3.*//okhttp3 4.9.1
import java.io.IOException
class NetworkTask : AsyncTask<String, Void, String>() {
override fun doInBackground(vararg params: String?): String {
val name = params[0] as String
Log.d("NetworkTask", "name: $name")
val url = "some url"
val requestBody = FormBody.Builder()
.add("name", name)
.build()
val request = Request.Builder()
.url(url)
.post(requestBody)
.build()
Log.d("NetworkTask", "Request URL: ${request.url}")
Log.d("NetworkTask", "Request method: ${request.method}")
val client = OkHttpClient()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
println("Failed to send POST request: ${e.message}")
}
override fun onResponse(call: Call, response: Response) {
println("POST request sent successfully $response")
}
})
return "Request sent"
}
}
我预计会收到如下格式的服务器日志:
body:{name: "John"}
但是,返回的服务器日志是:
body:{}
我正在使用翻译工具,所以如果有任何不清楚或尴尬的短语,请随时要求澄清。谢谢你。
添加
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
解决了我的问题。