使用Retrofit 2在多部分的PartMap请求中对同一参数使用多个值 [英] Using multiple values for the same param in a multipart's PartMap request with Retrofit 2
问题描述
我想在多部分查询中发送相同参数的多个值.这是我的代码:
I want to send multiple values of the same param in a multipart query. Here is my code:
接口:
@Multipart
@POST("user")
Observable<Void> updateUser(@PartMap() Map<String, RequestBody> partMap, @Part MultipartBody.Part photo);
此请求使我可以使用新图片和一些参数来更新用户.在参数中,我可以使用名为"skills []"的参数来指定用户的技能.为了指定数量可以变化的参数,我使用了一个HashMap.但是,对于HashMap,我无法使用相同的名称指定多个参数.
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.
即我做不到:
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.
如何指定一个参数的多个值.我可以使用Postman来测试请求.
How can I specify multiple values of a parameter. I have no problem doing it using Postman to test the request.
我尝试改用HashMap<String, List<RequestBody>>
:
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]
推荐答案
我仍然使用HashMap<String, RequestBody>
,但是我提供了不同的参数名称:
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);
}
这篇关于使用Retrofit 2在多部分的PartMap请求中对同一参数使用多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!