开发者

Ruby: HTTP.get_response from a website that does not exist

开发者 https://www.devze.com 2023-02-04 20:04 出处:网络
I have this code to check if the site is up or down: require \'net/http\' require \'uri\' res = Net::HTTP.get_response(URI.parse(\'http://www.saddsdsds.com/\'))

I have this code to check if the site is up or down:

require 'net/http'
require 'uri'

res = Net::HTTP.get_response(URI.parse('http://www.saddsdsds.com/'))

case res
when Net::HTTPSuccess, Net::HTTPRedirection
  # OK
  puts "ok"
else
  puts "ok-error"
end

res2 = Net::HTTP.get_response(URI.parse('http://www.sads.com/'))


case res2
when Net::HTTPSuccess, Net::HTTPRedirection
  # OK
  puts "ok"
else
  puts "ok-error"
end

However, the code works fine when the site is known but when the site is unknown (like the res example), the code breaks with this erorr:

`initialize': getaddrinfo: nodename nor 开发者_JAVA百科servname provided, or not known (SocketError)

How can I fix this so when the address does not exist, the code does not break?

Also, is this the best way to check if a site is online?

Thanks


Surround all of that code with a begin..rescue block:

begin
   ...
rescue SocketError => e
   puts "SocketError occurred: " + e
end
0

精彩评论

暂无评论...
验证码 换一张
取 消