如何在khttp中发送原始byteArray作为post请求的主体



从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-reo似乎被放弃了,所以你最好换到另一个lib。基本上,任何HTTP库都可以发送原始字节。至于燃料:它遵循模块化架构,不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": "u0001u0002u0003", 
"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"
})

最新更新