从khttp的来源看来,您无法将原始byteArray作为请求正文发送,因为它总是向其中添加填充。我也尝试过使用Fuel库,但是它需要与我的依赖项冲突的协程。
有人知道如何1)在khttp中发送原始字节主体,或2)另一个这样做的库
答案 0 :(得分:1)
您是对的。 As per their code如果您要发送的数据不是文件或流,它将是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"
})