User Agent in HTTP Requests, Ruby

I am new to Ruby. I tried looking at the online documentation, but I did not find anything that works. I would like to include the 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
+5
source share
2 answers

Amir F is true that you can use another HTTP client, such as RestClient or Faraday, but if you want to stick with the standard Ruby library, you can install your user agent:

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
+9
source

Net::HTTP - , -- - , :

require 'rest_client'

response = RestClient.get proggit_url
if response.code != 200
  # do something
end
+1

All Articles