Skip to main content

How to send JSON data in a request using OKHTTP in Kotlin Android

How to send JSON data in a request using OKHTTP in Kotlin Android.

Here's a step-by-step tutorial on how to send JSON data in a request using OKHTTP in Kotlin Android.

Step 1: Add dependencies

First, you need to add the OKHTTP dependency to your project. Open your app-level build.gradle file and add the following line of code to the dependencies block:

implementation 'com.squareup.okhttp3:okhttp:4.9.0'

Make sure to sync your project after adding the dependency.

Step 2: Create a JSON object

To send JSON data in a request, you need to create a JSON object with the data you want to send. You can do this using the JSONObject class from the org.json package.

val jsonObject = JSONObject()
jsonObject.put("key1", "value1")
jsonObject.put("key2", "value2")

Replace "key1", "value1", "key2", and "value2" with your own key-value pairs.

Step 3: Create an OKHTTP client

Next, you need to create an instance of the OKHTTP client. You can do this by creating a OkHttpClient object.

val client = OkHttpClient()

Step 4: Create a request body

To send JSON data in the request, you need to create a request body with the JSON object. You can use the RequestBody class and its create method to achieve this.

val requestBody = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())

Step 5: Create a request

Now, you can create a request with the request body you created. You can use the Request class to create a request object.

val request = Request.Builder()
.url("https://example.com/api/endpoint")
.post(requestBody)
.build()

Replace "https://example.com/api/endpoint" with the actual URL of the API endpoint you want to send the request to.

Step 6: Send the request

Finally, you can send the request using the OKHTTP client you created earlier. You can use the newCall method to execute the request.

client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// Handle the failure case
}

override fun onResponse(call: Call, response: Response) {
// Handle the response
}
})

In the onFailure method, you can handle any errors that occur during the request. In the onResponse method, you can handle the response from the server.

That's it! You have now learned how to send JSON data in a request using OKHTTP in Kotlin Android.