我正在尝试找到一种方法来复制发送二进制数据负载并设置Content-Type: binary
头的HTTP请求,就像使用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。有人之前做过这件事吗?还是宝石设计的目的不可能实现?
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
["14", "00", "00", "00", "70", "69", "6e", "67", "00", "00"]
的数组。也许你更想要的是%w[14 00 00 00 70 69 6e 67 00 00].map { |h| h.to_i(16) }.map(&:chr).join
。 - Gumbohex_data
上执行所有这些操作(gsub
、pack
、map
等)?"\x14\x00\x00\x00\x70\x69\x6e\x67\x00\x00"
将产生完全相同的结果。 - Jordan Running%w[14 00 00 ...].map {|h| h.to_i(16) }.pack('c*')
比map.map.join
版本可以节省几个操作。 - Jordan Running