英文:
How to send plain text as request body using okhttp in Android?
问题
I need to send a plain text as the request payload to my web app. But I can't make it to work with okhttp. I don't need complicated body builder that okhttp comes with such as FormBody.Builder() or MultipartBody.Builder(). I just need a simple text body attached to a POST http request header. Something like this:
val myBody = "my own body text that my server understands"
val request = Request.Builder()
.url(myUrl)
.post(myBody) //does not work.
.build()
okHttpClient.newCall(request)...
If okhttp can't do it, is there an alternative to use?
英文:
I need to send a plain text as the request payload to my web app. But I can't make it to work with okhttp. I don't need complicated body builder that okhttp comes with such as FormBody.Builder() or MultipartBody.Builder(). I just need a simple text body attached to a POST http request header. Something like this:
val myBody = "my own body text that my server understands"
val request = Request.Builder()
.url(myUrl)
.post(myBody) //does not work.
.build()
okHttpClient.newCall(request)...
If okhttp can't do it, is there an alternative to use?
答案1
得分: 0
你可以使用OkHttp。
你可以在示例中找到一个例子 - 发布一个字符串。
类似这样的代码:
private val client = OkHttpClient()
fun run() {
val postBody = """
|Releases
|--------
|
| * _1.0_ May 6, 2013
| * _1.1_ June 15, 2013
| * _1.2_ August 11, 2013
""".trimMargin()
val request = Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(postBody.toRequestBody(MEDIA_TYPE_MARKDOWN))
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body!!.string())
}
}
companion object {
val MEDIA_TYPE_MARKDOWN = "text/x-markdown; charset=utf-8".toMediaType()
}
英文:
You can use OkHttp.
You can find an example in recipes - Posting a String
Something like this:
private val client = OkHttpClient()
fun run() {
val postBody = """
|Releases
|--------
|
| * _1.0_ May 6, 2013
| * _1.1_ June 15, 2013
| * _1.2_ August 11, 2013
|""".trimMargin()
val request = Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(postBody.toRequestBody(MEDIA_TYPE_MARKDOWN))
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body!!.string())
}
}
companion object {
val MEDIA_TYPE_MARKDOWN = "text/x-markdown; charset=utf-8".toMediaType()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论