Upgrade: what sets @Field and @Body apart

In some email requests, I don't know when to use @Field, when to use @Body. How is the difference between:

@POST("users/register") Call<String> register(@Body RequestBody registerRequest); 

and

 @POST("users/register") Call<String> register(@Field String id, @Field String pass); 

Is it possible to use @Body instead of @Field and vice versa? If not, why? And how do you know this case, use @Body, otherwise use @Field?

Could you give me some examples and explain, thanks.

+5
source share
2 answers

@Body - Sends Java objects as the request body.

@Field - send data in urlencoded form. This requires the @FormUrlEncoded annotation associated with this method. The @Field parameter @Field works with POST. @Field required parameter required. In cases where @Field is optional, we can use @Query and pass a null value.

+6
source

Both are used to publish data only, but they have the following difference -

@Body annotations define a single request body.

  interface Foo { @POST("/jayson") FooResponse postJson(@Body FooRequest body); } 

This means that if you use @Body, it should only be a parameter. This is useful if you already have JsonObject and you want to send it as is with your api call.

Another way: you can send data using @Field and send the Place object as a JSON string.

 @POST("/post/addphoto/") public void addImage(@Field("image_url") String url, @Field("caption") String caption, @Field("google_place_id") String placeId, @Field("facebook_place") String place, Callback<UploadCallBack> response); 

Hope this helps ... :-)

+6
source

Source: https://habr.com/ru/post/1266568/


All Articles