Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit2: Use Body vs Query

I have a web-service method called change. I send UpdateStatusRequest objects to this web-service which defined as below:

public class UpdateStatusRequest {

    private String Status;

    public UpdateStatusRequest(String status) {
        Status = status;
    }
    public String getStatus() {
        return Status;
    }
}

When I use below API deceleration:

@POST("StatusUpdate")
Call<Status> change(@Query("Status") String status);

and then calling statusApi.change(request.getStatus()), it works well. It will call http://server-url/StatusUpdate?Status=Ready, when I pass Ready as status.

But using below declaration

@POST("StatusUpdate")
Call<Status> change(@Body UpdateStatusRequest status);

and then calling statusApi.change(request), it will call http://server-url/StatusUpdate and sends Status in request body. This will lead to 404 status code with error prompt Not Found.

I want to know what's wrong with my second call (since I supposed @Body acts like several @Query parameters which bundled together in the same object)?

like image 997
VSB Avatar asked Feb 03 '26 05:02

VSB


1 Answers

In Retrofit, @Body doesn't same as @Query.

  • @Body – Sends Java objects as request body.
  • @Query- Query parameter appended to the URL.null values are ignored.

But @Field is almost similar to @Body tag.

  • @Field – Send data as form-urlencoded. The @Field parameter works only with a POST.

For Example:

@POST("StatusUpdate")
Call<Status> change(@Field("Status") String Status);

But in your case, Your server is expecting the params to be passed in the URL(@Query).

Hope this explanation help.

like image 103
Mitesh Vanaliya Avatar answered Feb 05 '26 21:02

Mitesh Vanaliya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!