4

Have the below code working:

uri = URI.parse("http://www.ncdc.noaa.gov/cdo-web/api/v2/datasets/")
response = Net::HTTP.get_response(uri)

Now I also need to pass a header with this token hash in it:

token: "fjhKJFSDHKJHjfgsdfdsljh"

I cannot find any documentation on how to do this. How do I do it?

JPB
  • 53
  • 1
  • 4
  • 1
    There are many gems for Ruby that will make it much easier to use HTTP than Net::HTTP. I'd recommend researching those and picking one. Net::HTTP is really for those times when nothing else already exists. – the Tin Man Jul 05 '16 at 20:11
  • Also see: https://stackoverflow.com/questions/7478841/how-to-specify-http-request-header-in-openuri – Rimian Aug 03 '21 at 03:31

2 Answers2

4

get_response is a shorthand for making a request, when you need more control - do a full request yourself.

There's an example in ruby standard library here:

uri = URI.parse("http://www.ncdc.noaa.gov/cdo-web/api/v2/datasets/")
req = Net::HTTP::Get.new(uri)
req['token'] = 'fjhKJFSDHKJHjfgsdfdsljh'

res = Net::HTTP.start(uri.hostname, uri.port) {|http|
  http.request(req)
}
Vasfed
  • 18,013
  • 10
  • 47
  • 53
2

Though you surely could use Net::HTTP for this goal, gem excon allows you to do it far easier:

require 'excon'
url = 'http://www.ncdc.noaa.gov/cdo-web/api/v2/datasets/'
Excon.get(url, headers: {token: 'fjhKJFSDHKJHjfgsdfdsljh'})
hedgesky
  • 3,271
  • 1
  • 21
  • 36
  • 2
    That's just one of many gems which do this. [httparty](https://github.com/jnunemaker/httparty), [Faraday](https://github.com/lostisland/faraday) and [curb](https://github.com/taf2/curb) are also very popular. – tadman Jul 05 '16 at 22:08