Send JSON data using OkHttp using 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 medthods 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.toMediaTypeimport 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)
you need to create an object of type okhttp3.Request.Builder and add okhttp3.RequestBody via the post method
val okHttpClient: OkHttpClient = ...//val httpUrl = HttpUrl.parse("string url") ?: throw IllegalArgumentException("wrong url $url")//3.12.1val httpUrl = "string url".toHttpUrl()//4.0.1val httpUrlBuilder = httpUrl.newBuilder()val requestBuilder = Request.Builder().url(httpUrlBuilder.build())//val mediaTypeJson = MediaType.parse("application/json; charset=utf-8") ?: throw IllegalArgumentException("wrong media type")//3.12.1val mediaTypeJson = "application/json; charset=utf-8".toMediaType()//4.0.1val jsonString = "{\"jsondata\":0}"requestBuilder.post(jsonString.toRequestBody(mediaTypeJson)//4.0.1//RequestBody.create(mediaTypeJson, jsonString)//3.12.1)val call = okHttpClient.newCall(requestBuilder.build())... = call.execute()
Inside your build.gradle inside your dependencies, make sure you are using
dependencies { ... implementation "com.squareup.okhttp3:okhttp:4.0.1"}
Then, do a sync and the Android Studio IDE will offer you
import okhttp3.MediaType.Companion.toMediaType
After this you'll be able to
val contentType = "application/json".toMediaType()