Search code examples
ruby-on-railsrubyhttphttprequestnet-http

how do I include a header in an http request in ruby


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?


Solution

  • 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)
    }