加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 04:17:06 所属栏目:百科 来源:网络整理
导读:我试图找到一种方法来重现在有效负载中发送二进制数据的HTTP请求,以及设置Content-Type:二进制头,如下面的cURL命令: echo -e 'x14x00x00x00x70x69x6ex67x00x00' | curl -X POST -H 'Content-Type: binary' -H 'Accept: */*' -H 'Accept-Encod
我试图找到一种方法来重现在有效负载中发送二进制数据的HTTP请求,以及设置Content-Type:二进制头,如下面的cURL命令:
echo -e 'x14x00x00x00x70x69x6ex67x00x00' | 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进行响应.有没有人在之前完成它,或者它不可能用于设计宝石的目的?

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,sdch',:accept_language => 'en-US,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,'Accept-Language' => 'en-US,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

解决方法

我刚试过这个,它就像一个魅力:
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 = "x14x00x00x00x70x69x6ex67x00x00"
req.content_type = "application/octet-stream"

http.request(req)
# => #<Net::HTTPOK 200 OK readbody=true>

我使用RequestBin验证了数据正确发布.

Net::HTTP非常粗糙,使用起来并不是很有趣(例如,您必须手动格式化Cookie标头).它的主要好处是它在标准库中.像RestClient或HTTParty这样的宝石可能是更好的选择,而且我很确定它们中的任何一个都至少可以轻松处理二进制数据.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读