0

I Have JSON like this and i want to post this data using retrofit android

{ "status": "", "message": "", "data": { "request": { "textData": "123" } } }

and i don't know how to post this data, does anyone want to help me answer it?

  • 1
    you can make pojo class for the request and pass it as body by annotating it with @Body in your API interface – Bhavin Oct 27 '21 at 04:44
  • 1
    Does this answer your question? [Send Post Request with params using Retrofit](https://stackoverflow.com/questions/30180957/send-post-request-with-params-using-retrofit) – Nitish Oct 27 '21 at 04:49

1 Answers1

1

You can do it by creating a POJO or data class (in kotlin) of your request which makes doing things like this easier.

MyRequest.kt

data class MyRequest(
    var status: String,
    var message: String,
    var data: MyData
)


data class MyData(
    var request: RequestData
)


data class RequestData(
    var textData: String
)

MyApiInterface.kt

interface MyApiInterface {
    @POST("/my_url_endpoint")
    fun myRequest(
        @Body request: MyRequest
    ): Call<Unit>
}

MyActivity.kt

....

val request = MyRequest(
    "Ok",
    "My Message",
    MyData(
        request = RequestData("Hello World")
    )
 )

RetrofitClient.api.myRequest(request).enqueue(object: Callback<Unit> {
  override fun onResponse(call: Call<Unit>, response: Response<Unit>) {
      // TODO: some task
  }

  override fun onFailure(call: Call<Unit>, t: Throwable) {
      // TODO: some task
  }
})

....

after doing this request if you have added logging interceptor you can check that request being made with following body.

{"data":{"request":{"textData":"Hello World"}},"message":"My Message","status":"Ok"}

Bhavin
  • 577
  • 6
  • 11