okhttp3 RequestBody在Kotlin [英] okhttp3 RequestBody in Kotlin
本文介绍了okhttp3 RequestBody在Kotlin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要发送这样的请求正文:
I want to send a request body like this :
"email":{
"emailto":"foo@bar.com",
"emailfrom":"foo@bar.com",
"emailcc":"foo@bar.com",
"emailbcc":"foo@bar.com",
"emailsubject":"Subject",
"emailtag":"Information",
"emailtextbody":"---",
"attachments":[]
}
val formBody = FormBody.Builder()
.add("email", "Your message")
.build()
val request = Request.Builder()
.url(url)
.post(formBody)
.addHeader("_Token","")
.addHeader("Content-Type","application/json")
.build()
推荐答案
我强烈建议使用改装对于这种情况,但是如果您确实需要处理原始的Request
/Response
,那么您的解决方案将如下所示:
I highly suggest to use Retofit for such case, but if you really need to deal with raw Request
/Response
then your solution looks like:
val json = """
"email":{
"emailto":"${emailto}",
"emailfrom":"${emailfrom}",
"emailcc":"${emailcc}",
"emailbcc":"${emailbcc}",
"emailsubject":"${emailsubject}",
"emailtag":"${emailtag}",
"emailtextbody":"${emailtextbody}",
"attachments":[]
}
""".trimIndent()
val body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json)
val request = Request.Builder()
.url(url)
.post(body)
.build()
只需将方括号(例如${emailto}
)中的参数传递给您的函数即可.
Just pass parameters in brackets (e.g. ${emailto}
) to your function.
万一,如果您不想手动构建json,则可以使用 Gson 库
In case, if you don't want to build json manually, you can use Gson library.
data class EmailInfo(
val emailto: String,
val emailfrom: String,
val emailcc: String,
val emailbcc: String,
val emailsubject: String,
val emailtag: String,
val emailtextbody: String,
val attachments: List<Attachment>
)
data class EmailRequest(
val email: EmailInfo
)
...
val emailRequest = EmailRequest(
email = EmailInfo(
emailto = "...",
emailfrom = "...",
emailcc = "...",
emailbcc = "...",
emailsubject = "...",
emailtag = "...",
emailtextbody = "...",
attachments = ...
)
)
val json = Gson().toJson(emailRequest)
val body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json)
val request = Request.Builder()
.url(url)
.post(body)
.build()
}
这篇关于okhttp3 RequestBody在Kotlin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文