Ruby请求中的User-Agent

时间:2012-06-18 00:53:47

标签: ruby http user-agent

我对Ruby很新。我试过查看在线文档,但我还没有发现任何有用的东西。我想在以下HTTP请求中包含User-Agent,bot get_response()和get()。有人能指出我正确的方向吗?

  # 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

2 个答案:

答案 0 :(得分:9)

Amir F是正确的,您可能喜欢使用其他HTTP客户端,如RestClient或Faraday,但如果您想坚持使用标准的Ruby库,您可以像这样设置您的用户代理:

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

答案 1 :(得分:1)

Net::HTTP级别非常低,我建议使用rest-client gem - 它也会自动跟踪重定向并且更容易使用,即:

require 'rest_client'

response = RestClient.get proggit_url
if response.code != 200
  # do something
end
相关问题