我想发送一个这样的请求体:
"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()
答案 0 :(得分:5)
为使上面给出的答案更加清楚,这是使用扩展功能的方法。
如果您使用的是com.squareup.okhttp3:okhttp:4.0.1
,则不建议使用旧的创建 MediaType 和 RequestBody 对象的方法,并且不能在 Kotlin中使用 em>。
如果要使用扩展功能从字符串中获取 MediaType 对象和 ResponseBody 对象,请首先将以下几行添加到所需的类中使用它们。
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
您现在可以通过这种方式直接获取 MediaType 的对象
val mediaType = "application/json; charset=utf-8".toMediaType()
要获取 RequestBody 的对象,请先以这种方式将要发送的JSONObject转换为字符串。您必须将mediaType对象传递给它。
val requestBody = myJSONObject.toString().toRequestBody(mediaType)
答案 1 :(得分:3)
我强烈建议您使用Retofit作为此类案例,但如果您确实需要处理原始Request
/ Response
,那么您的解决方案如下:
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}
)传递给您的函数。
如果您不想手动构建json,可以使用Gson库。
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()
}