Send empty body in POST request in Retrofit

点点圈 提交于 2020-01-24 12:12:05

问题


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?


回答1:


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



回答2:


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



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



回答4:


use:

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

then call:

createPostRequest(new Object())


来源:https://stackoverflow.com/questions/44576046/send-empty-body-in-post-request-in-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!