make a http request with a custom body as binary in ruby

To make a HTTP request with a custom body as binary in Ruby, you can use the Net::HTTP module that comes with the standard library. Here's an example of how to make a POST request with a binary body:

main.rb
require 'net/http'

url = URI('https://example.com/path/to/endpoint')
body = "\x01\x23\x45\x67\x89" # binary data

request = Net::HTTP::Post.new(url)
request.body = body
request.content_type = 'application/octet-stream' # set the content type to binary

response = Net::HTTP.start(url.host, url.port, use_ssl: url.scheme == 'https') do |http|
  http.request(request)
end

puts response.body # the response body
411 chars
15 lines

In this example, we create a POST request with the Net::HTTP::Post.new method, set the binary body and set the content_type to 'application/octet-stream'. Then, we make the request using Net::HTTP.start and handle the response.

related categories

gistlibby LogSnag