okhttp3 RequestBody in Kotlin

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()
}