make a http request with a custom body as binary and return a binary response in ruby

To make a HTTP request with a custom body as binary and return a binary response in Ruby, you can use the Net::HTTP standard library. Here's an example code snippet:

main.rb
require 'net/http'

uri = URI('http://example.com/api')
body = "\x00\x01\x02\x03" # Your binary body data
headers = {'Content-Type'=> 'application/octet-stream'} # Set appropriate content-type header

response = Net::HTTP.start(uri.host, uri.port) do |http|
  http.post(uri, body, headers)
end

binary_response = response.body.bytes
333 chars
12 lines

In this code snippet, we first define the HTTP request URI and the binary data we want to send as the request body. We then set the appropriate Content-Type header for binary data.

Next, we make the HTTP POST request using Net::HTTP.start and pass in the URI, body and headers as arguments. The response object is returned and stored in the response variable.

Finally, we extract the binary response data by accessing response.body.bytes. We get the response as an array of bytes, which represents our binary data.

Note that in this example, we assume that the server endpoint expects a POST request with binary data in the HTTP body. The Content-Type header is set to 'application/octet-stream', which means a binary file format. You may need to set a different header depending on your server endpoint's requirements.

gistlibby LogSnag