Ruby - Send Get Request with Headers

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='
$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?

0

3 Answers

Using net/http as suggested by the question.

References:

  • Net::HTTP
  • Net::HTTP::get
  • Setting headers:
  • Net::HTTP::Get
  • Net::HTTPGenericRequest and Net::HTTPHeader (for methods that you can call on Net::HTTP::Get)

So, for example:

require 'net/http'    

uri = URI("")
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

3

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

require 'httparty'

url = '
headers = {
  key1: 'value1',
  key2: 'value2'
}

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

then run your .rb file..

4

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

Net::HTTP.get_response(URI('), { 'Accept' => 'text/html' })

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.