我正在使用OKHTTP并使用Multipart将图像发送到服务器。 我的代码如下:
RequestBody requestBody = null;
for (int i = 0; i < noOfItems; i++) {
requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
.addFormDataPart("func", "savepacket")
.addFormDataPart("userid", String.valueOf(mLoginPref.getInt("userId", 1)))
.addFormDataPart("packname", strPackname)
.addFormDataPart("image", str + ".png", RequestBody.create(MediaType.parse("image/png"), imagePath))
.addFormDataPart("count", String.valueOf(noOfItems))
.addFormDataPart("item_name" + String.valueOf(i + 1), al.get(i).getStrItemName())
.addFormDataPart("tag_item" + String.valueOf(i + 1), al.get(i).getStrItemTag())
.addFormDataPart("note" + String.valueOf(i + 1), al.get(i).getStrComment())
.addFormDataPart("image" + String.valueOf(i + 1), al.get(i).getStrItemName() + ".png", RequestBody.create(MediaType.parse("image/png"), al.get(i).getStrItemImage()))
.build();
}
mstrQRResponse = HttpUtils.postRun("pack", requestBody);
作为From代码,(al is ArrayList)你可以看到我必须发送带有单个Packname的多个项目,这就是我使用for循环的原因。
但实际上,由于requestBody在for循环内部覆盖,实际上只有最后一项保存在服务器上。
如何通过将所有项目添加到请求者来发送所有项目?
答案 0 :(得分:1)
试试这可能会对你有帮助。
MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
RequestBody requestBody = null;
for (int i = 0; i < noOfItems; i++) {
multipartBuilder
.addFormDataPart("func", "savepacket")
.addFormDataPart("userid", String.valueOf(mLoginPref.getInt("userId", 1)))
.addFormDataPart("packname", strPackname)
.addFormDataPart("image", str + ".png", RequestBody.create(MediaType.parse("image/png"), imagePath))
.addFormDataPart("count", String.valueOf(noOfItems))
.addFormDataPart("item_name" + String.valueOf(i + 1), al.get(i).getStrItemName())
.addFormDataPart("tag_item" + String.valueOf(i + 1), al.get(i).getStrItemTag())
.addFormDataPart("note" + String.valueOf(i + 1), al.get(i).getStrComment())
.addFormDataPart("image" + String.valueOf(i + 1), al.get(i).getStrItemName() + ".png", RequestBody.create(MediaType.parse("image/png"), al.get(i).getStrItemImage()));
}
requestBody = multipartBuilder.build();
mstrQRResponse = HttpUtils.postRun("pack", requestBody);