JPB
JPB

Reputation: 53

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?

Upvotes: 4

Views: 4631

Answers (2)

hedgesky
hedgesky

Reputation: 3311

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

Upvotes: 2

Vasfed
Vasfed

Reputation: 18444

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

Upvotes: 4

Related Questions