如何使用Ruby gem通过HTTP请求发送二进制数据?

ee7vknir  于 2023-04-20  发布在  Ruby
关注(0)|答案(2)|浏览(111)

我试图找到一种方法来重现HTTP请求,该请求在有效负载中发送二进制数据,并设置Content-Type: binary头,如以下带有cURL的命令:

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

我已经尝试过使用REST客户端(https://github.com/rest-client/rest-client)和HTTPClient(https://github.com/nahi/httpclient),但没有成功。使用下面的代码,服务器以HTTP 500响应。以前有人这样做过吗?或者不可能达到gem的设计目的?
Ruby代码:

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

更新(有一个可能的解决方案)

最后,我使用HTTParty运行了请求(遵循@DemonKingPiccolo给出的指导),并且成功了。代码如下:

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

正文也可以按照@gumbo的建议写成:

%w[14 00 00 00 70 69 6e 67 00 00].map { |h| h.to_i(16) }.map(&:chr).join
bfhwhh0e

bfhwhh0e1#

我试了一下,它就像一个魅力:

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>

我使用RequestBin验证了数据正确POST。
Net::HTTP非常粗糙,使用起来也没什么乐趣(例如,你必须手动格式化你的Cookie头)。它的主要好处是它在标准库中。像RestClient或HTTParty这样的gem可能是一个更好的选择,我很确定它们中的任何一个都可以轻松地处理二进制数据。

k10s72fa

k10s72fa2#

这里的推理略有不同,但希望能有所帮助。
我的HTTP请求只接受application/json类型,因此需要将二进制数据显示为PDF文件,通过请求体发送。
从二进制数据中创建一个临时文件,并使用HTTParty通过请求发送该文件,如下所示:

pdf_file = binary_data # can use gem like WickedPdf.new.pdf_from_string(content)

Tempfile.create(["file-name", ".pdf"], binmode: true) do |temp_file|
   temp_file.write(pdf_file)
   body = { "document" : File.open(temp_file) }
   HTTParty.post(url, headers: { "Content-Type": "application/json" }, body: body)
end

About ruby's temp file

相关问题