在Retrofit中一起使用@Field和@Body参数 [英] Use @Field and @Body parameters in Retrofit together

查看:539
本文介绍了在Retrofit中一起使用@Field和@Body参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Retrofit将一些数据发布到后端.我需要发送3个字符串和一个自定义Place对象.这是我在做什么:

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.

当我使用 @FormUrlEncoded 时,就像这样:

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

我收到此错误:

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

我如何使其工作?

推荐答案

最后,使其工作了.@Body和@Field不能一起使用.如果使用@Body,则它应该是唯一的参数,并且不能与@FormUrlEncode或@MultiPart结合使用.所以放弃了这个主意.另一种选择是仅使用@Field并将Place对象作为JSON字符串发送.

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.

这是我对API接口所做的:

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

这就是我创建要发送给 facebook_place 字段的值的方法:

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

这篇关于在Retrofit中一起使用@Field和@Body参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆