Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User-Agent in HTTP requests, Ruby

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
like image 857
hodgesmr Avatar asked Jun 18 '12 00:06

hodgesmr


2 Answers

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
like image 67
innonate Avatar answered Oct 17 '22 07:10

innonate


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
like image 29
Amir Avatar answered Oct 17 '22 05:10

Amir