2009-12-01 70 views
0

我想看看是否存在一個URL。這裏是我的代碼這樣做:(導軌)與URL驗證奇怪的問題

validate :registered_domain_name_exists 

private 

def registered_domain_name_exists 
    if url and url.match(URI::regexp(%w(http https))) then 
    begin # check header response 
     case Net::HTTP.get_response(URI.parse(url)) 
     when Net::HTTPSuccess then true 
     else errors.add(:url, "URL does not exist") and false 
     end 
    rescue # DNS failures 
     errors.add(:url, "URL does not exist") and false 
    end 
    end 
end 

但是,此代碼失敗。它說http://www.biorad.com不是一個有效的網站。這是絕對不正確的。此外,知道http://www.biorad.com只是將您重定向到http://www.bio-rad.com/evportal/evolutionPortal.portal我也試過這個URL,而且也失敗了。再次,我知道這是不可能的。我的代碼有什麼問題?

回答

0

您給出的每個示例網址都是重定向(http狀態代碼301或302)。你的代碼只考慮http狀態代碼2xx是成功的。添加另一個案例:

when Net::HTTPRedirection then true 

更新:請注意,使用HTTP HEAD而不是GET將在整個網絡中傳輸更少的數據。

uri = URI.parse(url) 
response = Net::HTTP.start(uri.host, uri.port) {|http| 
    http.head('/') 
}