Bob
Bob

Reputation: 31

How do you send raw byteArray as body of post request in khttp?

From the source of khttp it seems that you cant send raw byteArray as body of request because it always adds paddding to it. I've also tried using the Fuel library but it requires coroutines that conflict with my dependencies.

Does anyone know how to either 1) send raw bytes body in khttp or 2) another library that does

Upvotes: 3

Views: 2335

Answers (1)

madhead
madhead

Reputation: 33441

You're right. As per their code if the data you're sending is not file or stream it will be toString()'d which is not what you want. So, you may try providing a ByteArrayInputStream instead of ByteArray:

val response = post(
    "https://httpbin.org/anything",
    data = ByteArrayInputStream(byteArrayOf(1, 2, 3)),
    headers = mapOf("Content-Type" to "application/octet-stream")
)

Thus you'll send bytes as is.

BTW, khttp repo seems to be abandoned, so you'd better switch to another lib. Basically, any HTTP library can send raw bytes. As for the Fuel: it follows modular architecture and does not 100% require you to use coroutines:

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)

You'll see your byte array (in 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"
})

Upvotes: 1

Related Questions