2012-06-18 91 views
5

我對Ruby很新穎。我試着查看在線文檔,但我還沒有找到任何有效的工具。我想在下面的HTTP請求中包含用戶代理,bot get_response()和get()。有人能指引我朝着正確的方向嗎?HTTP請求中的用戶代理,Ruby

# 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 
+0

我認爲這是解決您的問題:http://www.dzone.com/snippets/send-custom-headers-ruby或http://stackoverflow.com/questions/587559/ruby-how-to-make -an-http-get-with-modified-headers – nhahtdh

回答

9

Amir F是正確的,你可以使用RestClient或Faraday等其他HTTP客戶端,但如果您想要使用標準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 
+0

謝謝!這似乎已經奏效! – hodgesmr

+0

在ruby 1.9.3上,如果我這樣做了'add_field',我最終得到了一個像'Ruby,My User Agent Dawg'這樣的用戶代理。 –

1

Net::HTTP是非常低的水平,我會建議使用rest-client gem - 它也將進行重定向自動,更容易讓你一起工作,即:

require 'rest_client' 

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