Reputation: 1314
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?
Upvotes: 7
Views: 18381
Reputation: 1
Following one is the easiest one I believe.
"{}".toRequestBody() // here "{}" will work like an empty json body.
// For Example:
val requestBody = "{}".toRequestBody()
val response = apiService.sendData(requestBody)
Upvotes: 0
Reputation: 1021
Heres the answer in Kotlin:
@POST("CountriesList")
fun getCountriesNew(@Body body: HashMap<String, String>) : Call<CountryModel>
val call = RetrofitClient.apiInterface.getCountriesNew(HashMap())
Upvotes: 0
Reputation: 276
An empty Object does it for Kotlin:
interface ApiService {
@POST("your.url")
fun createPostRequest(@Body body: Any = Object()): Call<YourResponseType>
}
Upvotes: 11
Reputation: 2479
use:
@POST("something")
Call<MyResponse> createPostRequest(@Body Object o);
then call:
createPostRequest(new Object())
Upvotes: 2
Reputation: 31
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);
Upvotes: 3
Reputation: 1463
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())
Upvotes: 6
Reputation: 2382
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);
Upvotes: 4