简体   繁体   中英

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 :

{ "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.

Here is a photo of what I observed:

在此处输入图片说明

Their documentation only states that "attachment" should be an object.

在此处输入图片说明

Is it possible at all to send a POJO object in a multipart-form request? My REST Interface looks like this:

@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:

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 .

Have you tried 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,

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:

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM