User-Agent in HTTP requests, Ruby

2019-06-21 01:36发布

问题:

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

回答1:

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


回答2:

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