7

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?

fwind
  • 1,274
  • 4
  • 15
  • 32

6 Answers6

8

An empty Object does it for Kotlin:

interface ApiService {
    @POST("your.url")
    fun createPostRequest(@Body body: Any = Object()): Call<YourResponseType>
}
Frans Hanyane
  • 237
  • 2
  • 12
6

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())
Gautam Kumar
  • 1,385
  • 14
  • 17
4

Empty class will do the trick:

class EmptyRequest {
    public static final EmptyRequest INSTANCE = new EmptyRequest();
}

interface My Service {

    @POST("my/url")
    Call<MyResponse> createPostRequest(@Body EmptyRequest request);

}

myService.createPostRequest(EmptyRequest.INSTANCE);
ledniov
  • 2,302
  • 3
  • 21
  • 27
3

Old question, but I found a more suitable solution by using a okhttp3.Interceptor that adds an empty body if no body is present. This solution does not require you to add an extra parameter for an empty @Body.

Example:

Interceptor interceptor = chain -> {
    Request         oldRequest = chain.request();
    Request.Builder newRequest = chain.request().newBuilder();

    if ("POST".equals(oldRequest.method()) && (oldRequest.body() == null || oldRequest.body().contentLength() <= 0)) {
        newRequest.post(RequestBody.create(MediaType.parse("application/json"), "{}"));
    }

    return chain.proceed(newRequest.build());
};

You can then create an instance of your service like so:

OkHttpClient.Builder client = new OkHttpClient.Builder();
client.addInterceptor(interceptor);

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("YourURL")
        .client(client.build())
        .build();

MyService service = retrofit.create(MyService.class);
2

use:

@POST("something")
Call<MyResponse> createPostRequest(@Body Object o);

then call:

createPostRequest(new Object())
Mahdi Moqadasi
  • 2,029
  • 4
  • 26
  • 52
0

Heres the answer in Kotlin:

    @POST("CountriesList")
fun getCountriesNew(@Body body: HashMap<String, String>) : Call<CountryModel>

      val call = RetrofitClient.apiInterface.getCountriesNew(HashMap())
Osama Ibrahim
  • 995
  • 10
  • 13