Use the @Field and @Body options in Retrofit together

I am using Retrofit to POST some data for my back-end. I need to send 3 lines and one custom Place object. That's what I'm doing:

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

In doing so, I get this error:

 @Field parameters can only be used with form encoding. 

And when I use @FormUrlEncoded , like this:

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

I get this error:

 @FormUrlEncoded or @Multipart can not be used with @Body parameter. 

How can I make it work?

+5
source share
1 answer

Finally, he earned. @Body and @Field cannot be used together. If @Body is used, it must be the only parameter, and it cannot be combined with @FormUrlEncode or @MultiPart. So lowered this idea. Another option is to use only @Field and send the Place object as a JSON string.

Here is what I did for the API:

 @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); 

And this is how I created the value to send for the facebook_place field:

 Place place = ... Gson gson = new GsonBuilder().disableHtmlEscaping().create(); String placeJSON = gson.toJson(place); 
+3
source

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


All Articles