Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send empty body in POST request in Retrofit

My api expects an empty json body ({ }) when making post requests. How do I set this up in Retrofit and Jackson?

I tried passing null, and empty string, and "{}" but could not get this to work.

@POST(my/url)
Call<MyResponse> createPostRequest(@Body Object empty);

How can I set an empty JSON body?

like image 846
fwind Avatar asked Jun 15 '17 20:06

fwind


People also ask

Can you send an empty body in a post request?

As per my understanding, you are still able to send post request with empty body and receiving an error code from backend. So you check backend program not to send 404 instead accept your request. Use body: Uint8List(0), but note that then your content type is likely wrong since an empty body wouldn't have a JSON type.

How do you send an object in post request in retrofit?

You can send it with help of @FormUrlEncoded for example : @FormUrlEncoded @Headers("Content-Type: application/json") @POST("getclass/") Call<ExampleClass> getExampleClass(@Field("id") int id, @Field("name") String name); but I think your way is easiest and right one.

Is request body mandatory for post request?

A POST request requires a body in which you define the data of the entity to be created. A successful POST request would be a 200 response code.


2 Answers

An empty Object does it for Kotlin:

interface ApiService {
    @POST("your.url")
    fun createPostRequest(@Body body: Any = Object()): Call<YourResponseType>
}
like image 186
JustFrago Avatar answered Sep 22 '22 07:09

JustFrago


try this . It worked for me now.

@POST(my/url)
Call<MyResponse> createPostRequest(@Body Hashmap );

while using this method pass new HasMap as paremater

apiservice.createPostRequest(new HashMap())
like image 41
Gautam Kumar Avatar answered Sep 19 '22 07:09

Gautam Kumar