【发布时间】:2018-10-03 10:21:08
【问题描述】:
我有一个 API,我必须在其中发送普通字段和图像。为了调用 API,我正在使用 Retrofit。为了发送多部分请求,我使用了 Multipart Body Builder 方法。下面是相同的代码。
val builder = MultipartBody.Builder()
builder.setType(MultipartBody.FORM)
var jsonArray = JSONArray()
for ((index, value) in lineItems.withIndex()) {
var jsonObject = JSONObject()
jsonObject.accumulate("Room_id", lineItems[index].roomId)
jsonObject.accumulate("jobTitle", lineItems[index].jobTitle)
jsonObject.accumulate("floorLevel", lineItems[index].floorLevel)
jsonObject.accumulate("jobTrade", lineItems[index].jobArea)
jsonObject.accumulate("jobWork", lineItems[index].jobWork)
jsonObject.accumulate("desc", lineItems[index].desc)
jsonObject.accumulate("isFixed", lineItems[index].isFixed)
jsonObject.accumulate("hourlyCost", lineItems[index].cost)
jsonObject.accumulate("hourlyTotal", lineItems[index].total)
jsonObject.accumulate("hourlyDuration", lineItems[index].duration)
jsonObject.accumulate("fixedCost", lineItems[index].fixedCost)
if (lineItems[index].lineItemId!="") {
jsonObject.accumulate("_id", lineItems[index].lineItemId)
}
jsonArray.put(jsonObject)
Log.d("json array",jsonArray.toString())
}
builder.addFormDataPart("lineHeight", jsonArray.toString())
for ((i, value) in lineItems.withIndex()) {
var imageList = ArrayList<String>()
if (lineItems[i].imageList!=null && lineItems[i].imageList!!.size>0) {
imageList = lineItems[i].imageList!!
for ((j, path) in imageList.withIndex()) {
if (!imageList[j].contains("http")) {
val file = File(path)
val requestFile =
RequestBody.create(MediaType.parse("image/"+
file.name.substring(file.name.indexOf(".")+1)), file)
val body = MultipartBody.Part.createFormData("photos" + i,
file.name, requestFile)
builder.addPart(body)
}
}
}
}
val requestBody = builder.build()
当我调用上述 API 时,我得到:
502 错误网关
http://18.222.231.171/api/lineheight/5bb45c4485453079ebb14b15 (4637ms)
服务器:nginx/1.10.3 (Ubuntu)
日期:格林威治标准时间 2018 年 10 月 3 日星期三 10:31:23
内容类型:text/html
内容长度:182
连接:保持活动
502 网关错误502 错误网关
nginx/1.10.3 (Ubuntu)
PS:- api 在 iOS 和 Postman 中都能正常工作
这里是调用代码:
fun addLineItems(@Header("Authorization") token: String,
@Path("jobId") jobId: String,
@Body body: okhttp3.RequestBody): Call<Response>
我与一位网络服务人员确认,当我从应用程序调用此 API 时,他们在日志中什么也得不到,而当从 Postman 调用同样的 API 时,日志会显示。
【问题讨论】:
-
你找到解决办法了吗?
标签: android retrofit2 multipartform-data