Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use @Field and @Body parameters in Retrofit together

I am using Retrofit to POST some data to my back-end. I need to send 3 Strings and one custom Place object. Here is what I am 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);

With this, I am getting 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 do I make it work?

like image 577
Amit Tiwari Avatar asked Dec 20 '15 08:12

Amit Tiwari


1 Answers

Finally, made it work. @Body and @Field can not be used together. If @Body is being used, it should be the only parameter and it can not be combined with @FormUrlEncode or @MultiPart. So dropped that idea. Another option was to use only @Field and send the Place object as a JSON string.

Here is what I did for API interface:

@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 be sent for facebook_place field:

Place place = ...
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String placeJSON = gson.toJson(place);
like image 147
Amit Tiwari Avatar answered Oct 31 '22 15:10

Amit Tiwari