使用 Retrofit 2 在多部分的 PartMap 请求中为同一参数使用多个值
Using multiple values for the same param in a multipart's PartMap request with Retrofit 2
我想在多部分查询中发送同一参数的多个值。这是我的代码:
接口:
@Multipart
@POST("user")
Observable<Void> updateUser(@PartMap() Map<String, RequestBody> partMap, @Part MultipartBody.Part photo);
此请求允许我使用新图片和一些参数更新用户。在参数中,我可以使用名为 "skills[]" 的参数指定用户的技能。为了指定数量可变的参数,我使用了 HashMap;但是对于 HashMap 我不能使用相同的名称指定多个参数。
即我做不到:
for(Integer skill : skills) {
RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), skill.toString());
map.put("skills[]", body);
}
因为地图只接受同一个键的一个值。
如何为一个参数指定多个值。我使用 Postman 测试请求没有问题。
我尝试使用 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);
但是好像不支持。创建的查询包含请求主体的空值:
Content-Disposition: form-data; name="skills[]"
Content-Transfer-Encoding: binary
Content-Type: application/json; charset=UTF-8
Content-Length: 16
[null,null,null]
使用它来创建文本 RequestBody 对象:
RequestBody userPhone = RequestBody.create(MediaType.parse("text/plain"), phoneNumber);
RequestBody userEmail = RequestBody.create(MediaType.parse("text/plain"), email);
希望对您有所帮助。
已修复,感谢 Andy Developer
我仍然使用 HashMap<String, RequestBody>
但我提供了不同的参数名称:
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);
}
我想在多部分查询中发送同一参数的多个值。这是我的代码:
接口:
@Multipart
@POST("user")
Observable<Void> updateUser(@PartMap() Map<String, RequestBody> partMap, @Part MultipartBody.Part photo);
此请求允许我使用新图片和一些参数更新用户。在参数中,我可以使用名为 "skills[]" 的参数指定用户的技能。为了指定数量可变的参数,我使用了 HashMap;但是对于 HashMap 我不能使用相同的名称指定多个参数。
即我做不到:
for(Integer skill : skills) {
RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), skill.toString());
map.put("skills[]", body);
}
因为地图只接受同一个键的一个值。
如何为一个参数指定多个值。我使用 Postman 测试请求没有问题。
我尝试使用 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);
但是好像不支持。创建的查询包含请求主体的空值:
Content-Disposition: form-data; name="skills[]"
Content-Transfer-Encoding: binary
Content-Type: application/json; charset=UTF-8
Content-Length: 16
[null,null,null]
使用它来创建文本 RequestBody 对象:
RequestBody userPhone = RequestBody.create(MediaType.parse("text/plain"), phoneNumber);
RequestBody userEmail = RequestBody.create(MediaType.parse("text/plain"), email);
希望对您有所帮助。
已修复,感谢 Andy Developer
我仍然使用 HashMap<String, RequestBody>
但我提供了不同的参数名称:
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);
}