Ruby请求中的User-Agent [英] User-Agent in HTTP requests, Ruby

查看:165
本文介绍了Ruby请求中的User-Agent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

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

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

这篇关于Ruby请求中的User-Agent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆