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?

2
  • 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. Commented Jul 5, 2016 at 20:11
  • Also see: stackoverflow.com/questions/7478841/… Commented Aug 3, 2021 at 3:31

2 Answers 2

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)
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but doesn't that send the request twice? When you call Net::Http.new, doesn't that send a request?
@JPB no, it initialises the request, connects to server and then sends the request.
This doesn't work anymore. Probably a https (SSL) issue.
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'})

1 Comment

That's just one of many gems which do this. httparty, Faraday and curb are also very popular.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.