3

In C# it was fairly simple and didn't take more than a couple minutes to google:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(@"http://www.example.com?q=someValue");
request.Headers.Add("Authorization: OAuth realm=\"example.com\" oauth_consumer_key=\"BCqrstoO\" ... so on and so forth");
string resultString = "";
using (StreamReader read = new StreamReader(request.GetResponse().GetResponseStream(), true))
{
    resultString = read.ReadToEnd();
}

Trying to do it in Ruby hasn't quite been as straight forward (or is just something stupid that I'm missing). I have been looking and the closest things I've come to finding my answer are How to make an HTTP GET with modified headers? and Send Custom Headers in Ruby.

So my problem, I suppose, boils down to

  1. How do I set the headers as just a just a straight forward string?
  2. Why do these two examples show headers formatted the way they are?
  3. Is what I'm asking for even good convention and if not, how do I format what I'm trying to do in the convention these Ruby methods are asking for?

So far I tried the two examples and here's my most recent non-working attempt:

headers = "Authorization: OAuth realm=\"example.com\" oauth_consumer_key=\"BCqrstoO\" ... so on and so forth" 
uri = URI("www.example.com")
http = Net::HTTP.new(uri.host, uri.port)

http.get(uri.path, headers) do |chunk|
  puts chunk
end
Community
  • 1
  • 1
Niko
  • 4,158
  • 9
  • 46
  • 85
  • 1
    May help if you remove the C# tag and just ask about adding headers to an HTTP request in Ruby. In an HTTP request, headers are just key/value pairs separated by a colon. So in your example the key is 'Authorization' and the value mapped to that key is all the stuff to the right. – Despertar Dec 15 '12 at 04:53
  • What have you tried? Or, at least, what is the code you're currently using to make the request? – Andrew Marshall Dec 15 '12 at 04:55
  • @Despertar So essentially all I need need to set it in this fashion: 'Authorization' => 'OAuth realm=\"example.com\" oauth_consumer_key=\"BCqrstoO\" ... so on and so forth' ? – Niko Dec 15 '12 at 05:01
  • @PaulBakerSaltShaker Yep, that looks good. Diego's example below should be spot on what you are looking to do. You can add whatever key/value pairs you need to, such as the oauth one you are using. – Despertar Dec 15 '12 at 07:13

2 Answers2

5

Use open-uri. Example:

require 'open-uri'

open("http://www.ruby-lang.org/en/",
    "User-Agent" => "Ruby/#{RUBY_VERSION}",
    "From" => "foo@bar.invalid",
    "Referer" => "http://www.ruby-lang.org/") {|f|
    # ...
  }
Diego Basch
  • 12,764
  • 2
  • 29
  • 24
3

Just in case you check this at this point on time, the Net:HTTPRequest object allows you to add headers easily.

Net::HTTP.start(uri.host, uri.port) do |http|
    request = Net::HTTP::Get.new uri
    request['my-header'] = '1'
    http.request request do |response|
        puts response
    end
end
Miyamoto Akira
  • 327
  • 1
  • 7
  • 16