user4584963
user4584963

Reputation: 2523

Ruby - Send GET request with headers

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);

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?

Upvotes: 20

Views: 46205

Answers (3)

metaphori
metaphori

Reputation: 2811

Using net/http as suggested by the question.

References:

So, for example:

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

Note: if your response has HTTP result state 301 (Moved permanently), see Ruby Net::HTTP - following 301 redirects

Upvotes: 35

iBug
iBug

Reputation: 37227

As of Ruby 3.0, Net::HTTP.get_response supports an optional hash for headers:

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

Unfortunately this does not work for Ruby 2 (up to 2.7).

Upvotes: 9

Md. Farhan Memon
Md. Farhan Memon

Reputation: 6121

Install httparty gem, it makes requests way easier, then in your script

require 'httparty'

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

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

then run your .rb file..

Upvotes: 18

Related Questions