[英]How do you send data in a Request body using HttpURLConnection?
[英]How do you send raw byteArray as body of post request in khttp?
从 khttp 的来源看来,您无法将原始 byteArray 作为请求正文发送,因为它总是向其添加填充。 我也尝试过使用 Fuel 库,但它需要与我的依赖项冲突的协程。
有谁知道如何 1) 在 khttp 中发送原始字节正文或 2) 另一个库
你是对的。 根据他们的代码,如果您发送的数据不是文件或流,它将是toString()'d
这不是您想要的。 因此,您可以尝试提供ByteArrayInputStream
而不是ByteArray
:
val response = post(
"https://httpbin.org/anything",
data = ByteArrayInputStream(byteArrayOf(1, 2, 3)),
headers = mapOf("Content-Type" to "application/octet-stream")
)
因此,您将按原样发送字节。
顺便说一句, khttp repo似乎被放弃了,所以你最好切换到另一个库。 基本上,任何 HTTP 库都可以发送原始字节。 至于 Fuel:它遵循模块化架构,并不 100% 要求您使用协程:
val (request, response, result) = "https://httpbin.org/anything".httpPost()
.body(byteArrayOf(1, 2, 3))
.header(mapOf("Content-Type" to "application/octet-stream"))
.response()
println(response)
你会看到你的字节数组(在data
):
<-- 200 (https://httpbin.org/anything)
Response : OK
Length : 564
Body : ({
"args": {},
"data": "\u0001\u0002\u0003",
"files": {},
"form": {},
"headers": {
"Accept": "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2",
"Accept-Encoding": "compress;q=0.5, gzip;q=1.0",
"Cache-Control": "no-cache",
"Connection": "close",
"Content-Length": "3",
"Content-Type": "application/octet-stream",
"Host": "httpbin.org",
"Pragma": "no-cache",
"User-Agent": "Java/1.8.0_192"
},
"json": null,
"method": "POST",
"origin": "1.2.3.4",
"url": "https://httpbin.org/anything"
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.