I want to send a request body like this :
"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()
For more clarity on the answer given above, this is how you can use the extension functions.
If you are using com.squareup.okhttp3:okhttp:4.0.1
the older methods of creating objects of MediaType and RequestBody have been deprecated and cannot be used in Kotlin.
If you want to use the extension functions to get a MediaType object and a ResponseBody object from your strings, firstly add the following lines to the class in which you expect to use them.
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
You can now directly get an object of MediaType this way
val mediaType = "application/json; charset=utf-8".toMediaType()
To get an object of RequestBody first convert the JSONObject you want to send to a string this way. You have to pass the mediaType object to it.
val requestBody = myJSONObject.toString().toRequestBody(mediaType)
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()
Just pass parameters in brackets (e.g. ${emailto}
) to your function.
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With