我正在尝试将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请求并打印响应?
答案 0 :(得分:12)
根据问题的建议使用net/http
。
参考文献:
Net::HTTP
https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.html Net::HTTP::get
https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.html#method-c-get Net::HTTP::Get
https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP/Get.html Net::HTTPGenericRequest
https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTPGenericRequest.html和Net::HTTPHeader
https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTPHeader.html(适用于Net::HTTP::Get
可以调用的方法)所以,例如:
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) {|http|
http.request(req)
}
puts res.body # <!DOCTYPE html> ... </html> => nil
注意:如果您的res
ponse HTTP结果状态301(永久移动),请参阅Ruby Net::HTTP - following 301 redirects
答案 1 :(得分:7)
安装httparty
gem,它使请求变得更容易,然后在您的脚本中
require 'httparty'
url = 'http://someexample.com'
headers = {
key1: 'value1',
key2: 'value2'
}
response = HTTParty.get(url, headers: headers)
puts response.body
然后运行您的.rb
文件..