Abhijith Konnayil
Abhijith Konnayil

Reputation: 4666

How to use OKHTTP to make a post request in Kotlin?

I need to make a post request to an endpoint from my android project. I am using Kotlin. Will I need to create a separate OKHttpClient Class for this.

Upvotes: 8

Views: 27443

Answers (1)

heX
heX

Reputation: 785

Here's how you can achieve this:

val payload = "test payload"

val okHttpClient = OkHttpClient()
val requestBody = payload.toRequestBody()
val request = Request.Builder()
        .post(requestBody)
        .url("url")
        .build()
okHttpClient.newCall(request).enqueue(object : Callback {
    override fun onFailure(call: Call, e: IOException) {
        // Handle this
    }

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

Don't forget to import:

import okhttp3.RequestBody.Companion.toRequestBody

Upvotes: 19

Related Questions