I am trying to send JSON data to the server using the OKhttp library and having trouble figuring out the right syntax for it. Tried the solution provided in this post okhttp3 RequestBody in Kotlin The class is deprecated as of now.
Code
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.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)
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.1
val httpUrl = "string url".toHttpUrl()//4.0.1
val 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.1
val mediaTypeJson = "application/json; charset=utf-8".toMediaType()//4.0.1
val 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()
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