Retrofit: what is different between @Field and @Body

前端 未结 2 510
长发绾君心
长发绾君心 2020-12-28 14:47

In some post request, I don\'t know when to use @Field, when to use @Body. Like whats the difference between:

@POST(\"users/register\")
    Call

        
相关标签:
2条回答
  • 2020-12-28 15:20

    Both are used for posting data only, but they have following difference -

    The @Body annotation defines a single request body.

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

    That means if you are using @Body, it should be only parameter. It is helpful when you have already a JsonObject and you want to send it as it with you api call.

    Another way is, 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 it will help... :-)

    0 讨论(0)
  • 2020-12-28 15:34

    @Body – Sends Java objects as request body.

    @Field – send data as form-urlencoded. This requires a @FormUrlEncoded annotation attached with the method. The @Field parameter works only with a POST. @Field requires a mandatory parameter. In cases when @Field is optional, we can use @Query instead and pass a null value.

    0 讨论(0)
提交回复
热议问题