Jayant Pahuja
Jayant Pahuja

Reputation: 81

Send JSON data using OkHttp using Kotlin

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

Upvotes: 8

Views: 10619

Answers (3)

Joaquin Iurchuk
Joaquin Iurchuk

Reputation: 5627

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

Upvotes: 0

Devenom
Devenom

Reputation: 975

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)

Upvotes: 9

Stanley Wintergreen
Stanley Wintergreen

Reputation: 385

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

Upvotes: 6

Related Questions