gpt4 book ai didi

android - 将 multipart 与 for 循环一起使用

转载 作者:行者123 更新时间:2023-11-30 01:43:39 25 4
gpt4 key购买 nike

我正在使用 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);

从代码来看,(al 是 ArrayList)您可以看到我必须使用单个 Packname 发送多个项目,这就是我使用 for 循环的原因。

但是,由于 requestBody 在 for 循环中被覆盖,实际上只有最后一项被保存在服务器上。

如何将所有项目添加到 requestbody 来发送?

最佳答案

试试这个可能对你有帮助。

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);

关于android - 将 multipart 与 for 循环一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34063065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com