Ruby – 使用标头发送GET请求
我想用一个网站的api来使用ruby。 说明是发送带有标头的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
。
参考文献:
-
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 - 设置标题 : 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.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 # ... => nil
注意:如果您的res
ponse具有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
文件..