use*_*963 9 ruby http http-headers
我想用一个网站的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);
Run Code Online (Sandbox Code Playgroud)
我只是在命令提示符下使用安装在windows上的ruby的.rb文件.我在ruby文件中使用net/http.如何发送带标题的GET请求并打印响应?
met*_*ori 15
net/http按照问题的建议使用.
参考文献:
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-getNet::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)所以,例如:
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
Run Code Online (Sandbox Code Playgroud)
注意:如果您的response具有HTTP结果状态301(永久移动),请参阅301 Net :: HTTP - 遵循301重定向
从 Ruby 3.0 开始,Net::HTTP.get_response支持标头的可选哈希:
Net::HTTP.get_response(URI('http://www.example.com/index.html'), { 'Accept' => 'text/html' })
Run Code Online (Sandbox Code Playgroud)
不幸的是,这不适用于 Ruby 2(最高 2.7)。
安装httpartygem,它使请求更容易,然后在您的脚本中
require 'httparty'
url = 'http://someexample.com'
headers = {
key1: 'value1',
key2: 'value2'
}
response = HTTParty.get(url, headers: headers)
puts response.body
Run Code Online (Sandbox Code Playgroud)
然后运行你的.rb文件..
| 归档时间: |
|
| 查看次数: |
15430 次 |
| 最近记录: |