我想发送这样的请求正文:
"email":{
"emailto":"[email protected]",
"emailfrom":"[email protected]",
"emailcc":"[email protected]",
"emailbcc":"[email protected]",
"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()
为了更清楚上面给出的答案,这是您可以使用扩展功能的方式。
如果您正在使用
com.squareup.okhttp3:okhttp:4.0.1
创建 MediaType 和 RequestBody 对象的旧方法已被弃用,不能在 Kotlin 中使用。
如果您想使用扩展函数从您的字符串中获取一个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)
我强烈建议在这种情况下使用 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()
}