How to send binary data via HTTP request using Ruby gem?

I am trying to find a way to play an HTTP request that sends binary data in a payload, and also sets the Content-Type: binary header, for example the following cURL command:

 echo -e '\x14\x00\x00\x00\x70\x69\x6e\x67\x00\x00' | curl -X POST \ -H 'Content-Type: binary' \ -H 'Accept: */*' \ -H 'Accept-Encoding: gzip,deflate,sdch' \ -H 'Accept-Language: en-US,en;q=0.8,pt;q=0.6' \ -H 'Cookie: JSESSIONID=m1q1hkaptxcqjuvruo5qugpf' \ --data-binary @- \ --url 'http://202.12.53.123' \ --trace-ascii /dev/stdout 

I have already tried using the REST client ( https://github.com/rest-client/rest-client ) and HTTPClient ( https://github.com/nahi/httpclient ), but to no avail. Using the code below, the server responded with HTTP 500. Has anyone done this before or is it impossible for the purpose for which the gems were designed?

Ruby Code:

 require 'rest-client' request = RestClient::Request.new( :method => :post, :url => 'http://202.12.53.123', :payload => %w[14 00 00 00 70 69 6e 67 00 00], :headers => { :content_type => :binary, :accept => '*/*', :accept_encoding => 'gzip,deflate,sdch', :accept_language => 'en-US,en;q=0.8,pt;q=0.6', :cookies => {'JSESSIONID' => 'm1q1hkaptxcqjuvruo5qugpf'} } ) request.execute 

UPDATE (with one possible solution)

I ended up working with HTTParty (as directed by @DemonKingPiccolo) and it worked. Here is the code:

 require 'httparty' hex_data = "14 00 00 00 70 69 6e 67 00 00" response = HTTParty.post( 'http://202.12.53.123', :headers => { 'Content-Type' => 'binary', 'Accept-Encoding' => 'gzip,deflate,sdch', 'Accept-Language' => 'en-US,en;q=0.8,pt;q=0.6' }, :cookies => {'JSESSIONID' => 'm1q1hkaptxcqjuvruo5qugpf'}, :body => [hex_data.gsub(/\s+/,'')].pack('H*').force_encoding('ascii-8bit') ) puts response.body, response.code, response.message, response.headers.inspect 

The body can also be written as suggested by @gumbo:

 %w[14 00 00 00 70 69 6e 67 00 00].map { |h| h.to_i(16) }.map(&:chr).join 
+7
ruby
source share
1 answer

I just tried this and it worked like a charm:

 require "net/http" uri = URI("http://example.com/") http = Net::HTTP.new(uri.host, uri.port) req = Net::HTTP::Post.new(uri.path) req.body = "\x14\x00\x00\x00\x70\x69\x6e\x67\x00\x00" req.content_type = "application/octet-stream" http.request(req) # => #<Net::HTTPOK 200 OK readbody=true> 

I checked that the POSTed data is correct using RequestBin .

Net :: HTTP is very rough around the edges and not very fun to use (for example, you need to format the cookie headers manually). Its main advantage is that it is in the standard library. A gem such as RestClient or HTTParty might be the best choice, and I'm sure that any of them will process binary data at least as easily.

+6
source

All Articles