Using multiple values for the same param in a mult

2019-07-21 04:46发布

问题:

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.