Retrofit: what is different between @Field and @Body

人盡茶涼 提交于 2019-12-18 11:46:21

问题


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<String> register(@Body RequestBody registerRequest);

and:

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

Can I use @Body instead of @Field, and reverse ? If not, why ? And how to know this case use @Body, other case use @Field ?

Can you please give me some case and explain, thank you.


回答1:


@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.




回答2:


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... :-)



来源:https://stackoverflow.com/questions/43337068/retrofit-what-is-different-between-field-and-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!