简体   繁体   中英

Send empty body in POST request in Retrofit

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

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

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())

An empty Object does it for Kotlin :

interface ApiService {
    @POST("your.url")
    fun createPostRequest(@Body body: Any = Object()): Call<YourResponseType>
}

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);

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);

use:

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

then call:

createPostRequest(new Object())

Heres the answer in Kotlin:

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

      val call = RetrofitClient.apiInterface.getCountriesNew(HashMap())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM