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);
EmptyRequest
with singleton instance and pass it as parameter. – Glynda