问题描述
我正在尝试将 ruby 与网站的 api 一起使用.说明是发送带有标头的 GET 请求.这些是来自网站的说明和他们提供的示例 php 代码.我要计算 HMAC 哈希并将其包含在 apisign
标头下.
I am trying to use ruby with a website's api. The instructions are to send a GET request with a header. These are the instructions from the website and the example php code they give. I am to calculate a HMAC hash and include it under an apisign
header.
$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);
我只是在命令提示符下使用安装了 ruby 的 .rb 文件在 Windows 上.我在 ruby 文件中使用 net/http.如何发送带有标头的 GET 请求并打印响应?
I am simply using an .rb file with ruby installed on windows from command prompt. I am using net/http in the ruby file. How can I send a GET request with a header and print the response?
推荐答案
按照问题的建议使用 net/http
.
Using net/http
as suggested by the question.
参考资料:
Net::HTTP
https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.htmlNet::HTTP::get
https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.html#method-c-get- 设置标题:https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.html#class-Net::HTTP-label-Setting+Headers
Net::HTTP::Get
https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP/Get.htmlNet::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
上调用的方法)
Net::HTTP
https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.htmlNet::HTTP::get
https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.html#method-c-get- Setting headers: https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.html#class-Net::HTTP-label-Setting+Headers
Net::HTTP::Get
https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP/Get.htmlNet::HTTPGenericRequest
https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTPGenericRequest.html andNet::HTTPHeader
https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTPHeader.html (for methods that you can call onNet::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 - 跟随 301 重定向
Note: if your res
ponse has HTTP result state 301 (Moved permanently), see Ruby Net::HTTP - following 301 redirects
这篇关于Ruby - 发送带有标头的 GET 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!