2015-07-13 126 views
1

我试图发送使用RetrofitMultipart-form要求如下:如何使用Retrofit在Multipart-form请求中发送POJO对象?

{ "attachment": { 
    "file_cache": "....." 
    "original": "upload/image.png", 
    "versions": { 
     "small": "uploads/small_image.png" 
    } 
    }, 
    "content": "", 
    "id": 1 
} 

我不知道这是否是一个正确的请求,我应该被发送到API,因为它们的文档是很可怕,但我能够使用Chrome开发工具来研究API接收请求的方式以及响应方式,它似乎接受了JSON。

下面是我观察到的照片:

enter image description here

他们的文档只是说"attachment"应该是一个对象。

enter image description here

是否有可能在所有的multipart-form请求发送POJO对象?我的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); 

发送MultipartTypedOutput没有工作,既不用下面做的事:如何做到这一点

addMessage(...., @Part("attachment") POJOObject object, ...); 

任何想法?

如果我尝试使用Retrofit发送一个POJO对象,我将获得状态422无法处理的实体。

回答

1

我可以通过以下链接here来解决这个问题。

我没有意识到这一点,但为了送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); 

希望这可以帮助其他人出的道路。

1

你有没有试过TypedFile?如果不尝试这种方式,

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

对于TypedFile你可以通过附件这样,

File attachmentFile = new File("upload/image.png"); 
TypedFile attachmentTypedFile = new TypedFile("image/*", photoFile);