[英]How can I send a POJO object in a Multipart-form Request using Retrofit?
I am trying to send the following in a Multipart-form
request using Retrofit
: 我正在尝试使用Retrofit
在Multipart-form
请求中发送以下内容:
{ "attachment": {
"file_cache": "....."
"original": "upload/image.png",
"versions": {
"small": "uploads/small_image.png"
}
},
"content": "",
"id": 1
}
I don't know if this is a correct request I should be sending to the API, since their documentation is really horrible but I was able to use Chrome Dev Tools to study what the API was receiving request wise and how it was responding, it seems to accept that JSON. 我不知道这是我应该发送给API的正确请求,因为它们的文档确实很糟糕,但是我能够使用Chrome Dev Tools研究API明智地接收了什么以及它如何响应,它似乎接受JSON。
Here is a photo of what I observed: 这是我观察到的照片:
Their documentation only states that "attachment"
should be an object. 他们的文档仅声明"attachment"
应为对象。
Is it possible at all to send a POJO
object in a multipart-form
request? 是否可以通过multipart-form
请求发送POJO
对象? My REST Interface looks like this: 我的REST接口如下所示:
@Multipart
@POST("/v2/{type}/{id}/message.json")
void addMessage(@Path("type") String type,
@Path("id") int id,
@Part("content") String content,
@Part("attachment") MultipartTypedOutput multipartTypedOutput,
Callback<Post> callback);
Sending a MultipartTypedOutput
didn't work, neither did using the following: 发送MultipartTypedOutput
不起作用,也不使用以下命令:
addMessage(...., @Part("attachment") POJOObject object, ...);
Any ideas on how to accomplish this? 关于如何做到这一点的任何想法?
I get a status 422
un-processable entity if I try to send a POJO
object with Retrofit
. 如果尝试使用Retrofit
发送POJO
对象,则会得到状态422
无法处理的实体。
Have you tried TypedFile ? 您尝试过TypedFile吗? If not try this way, 如果不这样尝试
@Multipart
@POST("/v2/{type}/{id}/message.json")
void addMessage(@Path("type") String type,
@Path("id") int id,
@Part("content") String content,
@Part("attachment") TypedFile photoFile,
Callback<Post> callback);
For TypedFile you can pass attachment this way, 对于TypedFile,您可以通过这种方式传递附件,
File attachmentFile = new File("upload/image.png");
TypedFile attachmentTypedFile = new TypedFile("image/*", photoFile);
I was able to solve this by following this link here . 通过点击这里的链接,我能够解决这个问题 。
I was not aware of this but in order to send JSON
you need to setup your REST API Service
like so: 我不知道这一点,但是要发送JSON
您需要像这样设置REST API Service
:
@Multipart
@POST("/v2/{type}/{id}/message.json")
void addMessage(@Path("type") String type,
@Path("id") int id,
@Part("content") String content,
@Part("attachment[file_cache]") String fileCache,
@Part("attachment[original]") String original,
@Part("attachment[versions][small]") String small,
Callback<Post> callback);
Hopefully this helps someone else out down the road. 希望这可以帮助其他人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.