繁体   English   中英

Ruby - 发送带有标头的 GET 请求

[英]Ruby - Send GET request with headers

我正在尝试将 ruby​​ 与网站的 api 一起使用。 说明是发送带有标头的 GET 请求。 这些是来自网站的说明和他们提供的示例 php 代码。 我要计算 HMAC 哈希并将其包含在apisign标头下。

$apikey='xxx';
$apisecret='xxx';
$nonce=time();
$uri='https://bittrex.com/api/v1.1/market/getopenorders?apikey='.$apikey.'&nonce='.$nonce;
$sign=hash_hmac('sha512',$uri,$apisecret);
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$obj = json_decode($execResult);

我只是在命令提示符下使用在 Windows 上安装了 ruby​​ 的 .rb 文件。 我在 ruby​​ 文件中使用 net/http。 如何发送带有标头的 GET 请求并打印响应?

按照问题的建议使用net/http

参考:

因此,例如:

require 'net/http'    

uri = URI("http://www.ruby-lang.org")
req = Net::HTTP::Get.new(uri)
req['some_header'] = "some_val"

res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http|
  http.request(req)
}

puts res.body # <!DOCTYPE html> ... </html> => nil

注意:如果您的res具有HTTP 结果状态 301(永久移动) ,请参阅Ruby Net::HTTP - 以下 301 重定向

安装httparty gem,它使请求更容易,然后在你的脚本中

require 'httparty'

url = 'http://someexample.com'
headers = {
  key1: 'value1',
  key2: 'value2'
}

response = HTTParty.get(url, headers: headers)
puts response.body

然后运行你的.rb文件..

从 Ruby 3.0 开始, Net::HTTP.get_response支持标头的可选散列:

Net::HTTP.get_response(URI('http://www.example.com/index.html'), { 'Accept' => 'text/html' })

不幸的是,这不适用于 Ruby 2(最高 2.7)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM