5

I'm pretty new to Ruby. I've tried looking over the online documentation, but I haven't found anything that quite works. I'd like to include a User-Agent in the following HTTP requests, bot get_response() and get(). Can someone point me in the right direction?

  # Preliminary check that Proggit is up
  check = Net::HTTP.get_response(URI.parse(proggit_url))
  if check.code != "200"
    puts "Error contacting Proggit"
    return
  end

  # Attempt to get the json
  response = Net::HTTP.get(URI.parse(proggit_url))
  if response.nil?
    puts "Bad response when fetching Proggit json"
    return
  end
hodgesmr
  • 2,765
  • 7
  • 30
  • 41
  • I think this is the solution to your problem: http://www.dzone.com/snippets/send-custom-headers-ruby OR http://stackoverflow.com/questions/587559/ruby-how-to-make-an-http-get-with-modified-headers – nhahtdh Jun 18 '12 at 00:58

2 Answers2

9

Amir F is correct, that you may enjoy using another HTTP client like RestClient or Faraday, but if you wanted to stick with the standard Ruby library you could set your user agent like this:

url = URI.parse(proggit_url)
req = Net::HTTP::Get.new(proggit_url)
req.add_field('User-Agent', 'My User Agent Dawg')
res = Net::HTTP.start(url.host, url.port) {|http| http.request(req) }
res.body
Community
  • 1
  • 1
innonate
  • 159
  • 5
1

Net::HTTP is very low level, I would recommend using the rest-client gem - it will also follows redirects automatically and be easier for you to work with, i.e:

require 'rest_client'

response = RestClient.get proggit_url
if response.code != 200
  # do something
end
Amir
  • 1,882
  • 17
  • 22