2015-07-13 124 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);