【发布时间】:2019-07-19 06:20:03
【问题描述】:
我想为我的multipart request 使用Retrofit 库而不是HttpURLConnection 将图像发送到服务器。我的HttpURLConnection 请求由于某种原因无法正常工作。
但我在Retrofit 中有问题,我不知道如何将Session token 和API key 添加到我的请求中。
这是我对HttpURLConnection 的每个请求使用的解决方案(它适用于除多部分请求之外的所有请求):
val con = url.openConnection() as HttpURLConnection
con.apply {
requestMethod = method
useCaches = false
doOutput = true
doInput = true
addRequestProperty(HEADER_CONNECTION, "Keep-Alive")
addRequestProperty(HEADER_CACHE_CONTROL, "no-cache")
addRequestProperty(HEADER_CONTENT_TYPE, "multipart/form-data")
addRequestProperty("X-API-Key", apiType.apiKey)
addRequestProperty("X-Session", getServerSession())
}
这是我使用改造库的要求:
val f = File(app.cacheDir, filename)
f.createNewFile()
val fos = FileOutputStream(f)
fos.write(data)
fos.flush()
fos.close()
val reqFile = RequestBody.create(MediaType.parse("image/*"), f)
val body = MultipartBody.Part.createFormData("upload", f.name, reqFile)
val httpUrl = HttpUrl.Builder()
.scheme("https")
.host(mainUrl)
.addPathSegment(apiSegment)
.addQueryParameter("X-API-Key", apiType.apiKey)
.addQueryParameter("X-Session", getServerSession())
val service = Retrofit.Builder().baseUrl(httpUrl.build()).build().create(Service::class.java)
val req = service.postImage(body)
val response = req.execute()
我使用了addQueryParameter,因为我读到这是将这两个参数添加到标头的方法,但这只会影响我的 API 调用 URL,它会将 API 密钥和会话添加到 URL,这根本不被服务器识别。
更新:
我的邮政服务界面:
internal interface MultipartService {
@Multipart
@POST("{url}")
fun postImage(@Part image: MultipartBody.Part): Call<ResponseBody>
fun setEndpoint(@Path("url") endpoint: String): Call<ResponseBody>
}
更新:已修复
internal interface MultipartServicePost {
@POST("{url}")
@Multipart
fun postImage(@Part image: MultipartBody.Part, @Path(value = "url", encoded = true) endpoint: String): Call<ResponseBody>
}
【问题讨论】:
标签: android kotlin retrofit retrofit2 httpurlconnection