TheCodeDemon
TheCodeDemon

Reputation: 105

How to POST JSON data using OkHttp

I am using OkHttp in Kotlin to POST JSON data to my REST API endpoint. However, JSONParser().parse(request) is giving a bad request error. I think that there is some issue in the way I am passing data using OkHttp. Here is the relevant code:

val url = "http://10.0.2.2:8000/dummy/"

val JSON: MediaType? = MediaType.parse("application/json; charset=utf-8")

val JSONObjectString = "{\"name\":\"Mahesh\"}" //The data I want to send

var body:RequestBody = RequestBody.create(JSON, JSONObjectString)
val request = Request.Builder().post(body).url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
         val tm = response?.body()?.string()
         println(tm)
}

override fun onFailure(call: Call, e: IOException) {
         Log.d("Failed", "FAILED")
         e.printStackTrace()
}
})

On print(request.data) gives:

{'name':'Mahesh'}

So the request reaches the end point, but JSONParser().parse(request) gives a bad request error which I suppose happens when the data isn't in the correct format. Whats wrong with the way I am passing data?

Upvotes: 2

Views: 1321

Answers (1)

Yuri Schimke
Yuri Schimke

Reputation: 13488

The payload is in request.data so this should be parsed.

JSONParser().parse(request.data)

Upvotes: 1

Related Questions