从 khttp 的来源来看,您似乎无法将原始 byteArray 作为请求主体发送,因为它总是向其中添加填充。我也尝试过使用 Fuel 库,但它需要与我的依赖项冲突的协程。
有谁知道如何 1) 在 khttp 中发送原始字节正文或 2) 另一个执行此操作的库
最佳答案
你是对的。 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好像被废弃了,所以你最好换个lib。基本上,任何 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"
})
关于java - 你如何在 khttp 中发送原始 byteArray 作为 post 请求的主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53314886/