精華區beta Ruby 關於我們 聯絡資訊
出自我的 Blog http://lightyror.blogspot.com/2006/09/http-get.html 這裡有一段Check HTTP 狀態的程式 基本上是用 crontab 去跑就好 log function 大家就自由發揮吧,看你要寫到那邊都隨便你 值得注意的是 response 不能直接用 == 去判斷Net::HTTPSuccess或是其他的狀態 因為Net::HTTPSuccess是一種很像是 range 的 object 直接用 == 判斷會判斷不出來得 建議是用 case when 來判斷,他會使用 === 來判斷 但是如果你要用 if 來改寫的話 ,必須寫成 Net::HTTPSuccess === response 我覺得這樣比較不直覺 :p require 'net/http' url = 'http://www.example.com' response = Net::HTTP.get_response(URI.parse(url)) begin case response when Net::HTTPSuccess log 'OK' when Net::HTTPNotFound log '404 Error' when Net::HTTPInternalServerError log 'Internal Server Error' when Net::HTTPUnauthorized log 'Unauthorized' when Net::HTTPClientError log 'Client Error' when Net::HTTPRedirection log 'Redirect' when Net::HTTPInformation log 'Informantion' when Net::HTTPServerError log 'Server Error' when Net::HTTPUnknownResponse log 'Unknown Response' end rescue Timeout::Error log 'System Timeout' end 以下的 code 可以偵測這個網頁處於那種狀態 我特別將 404 error ,500 error 挑出來 因為他是最容易發現的錯誤,你可以根據這個錯誤去做判斷 基本上只要有 response ,不管是那門子的 HTTP error ,Ruby 是不會 raise error 的 你必須使用 response.error! 或是 response.value 去 raise error 這樣的特性也比較好 coding 但是最後,我們還是得去抓 Timeout::Error 為什麼?我們公司有一台 server ,跑 lighttpd 因為 lighttpd 會去 query application server 的 backend process 當backend process 掛掉的時候,他就不回應給 lighttpd 遇到這種情況 Lighttpd 就不回你錯誤訊息 這樣子,一定要抓 Timeout::Error 才能知道出了啥問題 參考自Introduction to Ruby Net::HTTP,寫的很好 HTTP Response 列表可以參考自 Ruby Manual -- lighty RoR 是一個介紹 lighttpd , SQLite , Ruby and Rails 的 Blog http://lightyror.blogspot.com/ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.230.108.209 ※ 編輯: giive 來自: 61.230.108.209 (09/23 09:06) > -------------------------------------------------------------------------- < 作者: giive (lala) 看板: Ruby 標題: HTTP 認證程式(不用 ssl ) 時間: Sat Sep 23 09:15:44 2006 出自我的Blog http://lightyror.blogspot.com/2006/09/http-ssl.html 本來以為上面那一隻 script 可以偵測公司各個 server 的狀態 :p 但是果然事情沒那麼簡單 有一台我架的 test server 裡面的網頁是開發階段的 需要避免閒雜人等進來了解研發機密 為求方便,直接使用 http auth 即可 好吧, 這一段是可以認證的 HTTP 程式 require 'net/http' url_address = 'http://www.example.com' url = URI.parse(url_address) req = Net::HTTP::Get.new(url.path) req.basic_auth 'user', 'password' res = Net::HTTP.start(url.host, url.port) { |http| http.request(req) } puts res.body -- lighty RoR 是一個介紹 lighttpd , SQLite , Ruby and Rails 的 Blog http://lightyror.blogspot.com/ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.230.108.209