Ruby请求中的User-Agent

hod*_*smr 5 ruby user-agent http

我是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
Run Code Online (Sandbox Code Playgroud)

小智 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
Run Code Online (Sandbox Code Playgroud)