Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit: Add a String List parameter to Multipart Request

I'm trying to add a String list parameter to a multi-part request.

Using Apache Http, I set the parameter like this:

MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(mpEntity);

for (User member : members) {
    mpEntity.addPart("user_ids[]", new StringBody(member.id.toString()));
}

How do I do this on Retrofit?

like image 656
dannyroa Avatar asked Mar 20 '14 23:03

dannyroa


1 Answers

Take a look at MultipartTypedOutput. I don't think there is a built-in support so you have to construct it yourself or write a Convertor.

At your service interface:

@POST("/url")
Response uploadUserIds(@Body MultipartTypedOutput listMultipartOutput);

At your caller:

MultipartTypedOutput mto = new MultipartTypedOutput();
for (String userId : userIds){
   mto.addPart("user_ids[]", new TypedString(userId));
}
service.uploadUserIds(mto);

This will construct similar result:

    Content-Type: multipart/form-data; boundary=49f201f1-7379-4390-9ea5-97d74e78bb63
    Content-Length: 820
    --49f201f1-7379-4390-9ea5-97d74e78bb63
    Content-Disposition: form-data; name="name"
    Content-Type: text/plain; charset=UTF-8
    Content-Length: 10
    Content-Transfer-Encoding: binary
    yourString
    --49f201f1-7379-4390-9ea5-97d74e78bb63
    Content-Disposition: form-data; name="name"
    Content-Type: text/plain; charset=UTF-8
    Content-Length: 10
    Content-Transfer-Encoding: binary
    yourString
    --49f201f1-7379-4390-9ea5-97d74e78bb63
    Content-Disposition: form-data; name="name"
    Content-Type: text/plain; charset=UTF-8
    Content-Length: 10
    Content-Transfer-Encoding: binary
    yourString
    --49f201f1-7379-4390-9ea5-97d74e78bb63
    Content-Disposition: form-data; name="name"
    Content-Type: text/plain; charset=UTF-8
    Content-Length: 10
    Content-Transfer-Encoding: binary
    yourString
    --49f201f1-7379-4390-9ea5-97d74e78bb63--
like image 141
Sergii Pechenizkyi Avatar answered Nov 14 '22 23:11

Sergii Pechenizkyi