Retrofit:将字符串列表参数添加到多部分请求

6

我是一名翻译,有关IT技术的内容需要我来为您进行翻译。

我正在尝试将字符串列表参数添加到多部分请求中。

使用Apache Http,我这样设置参数:

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()));
}

我该怎么在Retrofit上实现这个功能?
1个回答

2

请看MultipartTypedOutput。我认为它没有内置的支持,所以您需要自己构建它或编写一个Convertor

在您的服务接口中:

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

在您的调用者处:

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

这将构建类似的结果:
    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--

谢谢!我稍后会试一下。 - dannyroa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接