Using multiple values for the same param in a multipart's PartMap request with Retrofit 2

依然范特西╮ 提交于 2019-12-24 02:25:34

问题


I want to send multiple values of the same param in a multipart query. Here is my code:

Interface:

@Multipart
@POST("user")
Observable<Void> updateUser(@PartMap() Map<String, RequestBody> partMap, @Part MultipartBody.Part photo);

This request allow me to update a user with a new picture and some parameters. In the parameters I can specify the user's skills with a parameter named "skills[]". To specify the parameters that can vary in number I use a HashMap; however with a HashMap I cannot specify multiple parameters using the same name.

i.e. I cannot do:

for(Integer skill : skills) {
    RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), skill.toString());
    map.put("skills[]", body);
}

Because the map will only accept one value of the same key.

How can I specify multiple values of a parameter. I have no problem doing it using Postman to test the request.

I tried to use a HashMap<String, List<RequestBody>> instead:

List<RequestBody> bodies = new ArrayList<>();
for(Integer skill : skills) {
    RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), skill.toString());
    bodies.add(body);
}
map.put("skills[]", bodies);

but it seems that it's not supported. The query created contains null values for the request bodies:

Content-Disposition: form-data; name="skills[]"
Content-Transfer-Encoding: binary
Content-Type: application/json; charset=UTF-8
Content-Length: 16

[null,null,null]

回答1:


Fixed thanks to Andy Developer

I still use the HashMap<String, RequestBody> but I provide different parameters names:

for(int i = 0; i < skills.size(); i++) {
    Integer skill = skills.get(i);
    RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), skill.toString());
    map.put("skills[" + i + "]", body);
}



回答2:


Use this to create text RequestBody objects:

  RequestBody userPhone = RequestBody.create(MediaType.parse("text/plain"), phoneNumber);
  RequestBody userEmail = RequestBody.create(MediaType.parse("text/plain"), email);

Hope this helps.



来源:https://stackoverflow.com/questions/44387403/using-multiple-values-for-the-same-param-in-a-multiparts-partmap-request-with-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!