元は!url.nil? && !url.empty?
だけだったメソッドに、応答コードが200かどうかの部分を追加。
require 'net/http' def url_exist?(url) code = ->(url) { uri = URI.parse(url) Net::HTTP.start(uri.host, uri.port) { |http| http.get(uri.path) }.code } !url.nil? && !url.empty? && code.call(url) == "200" end
注意:url には URL として正しい文字列を渡さないと URI::InvalidURIError
エラーになりますorz
注意2:url 末尾には path が存在(uri.path.empty?
が false
)でないと http.get(uri.path)
でエラーになります
いろいろ対応出来るように改良
open-uri を使うことを想定しているのでレスポンスが Success のほか Redirection にも対応させました。これでほぼ無敵になった…はず 残念ながらこれだと https 未対応でした、対応版はさらに下へ。
require 'net/http' def url_exist?(url) res = ->(url) { begin uri = URI.parse(url) uri_path = uri.path.empty? ? "/" : uri.path Net::HTTP.start(uri.host, uri.port) { |http| http.get(uri_path) } rescue TypeError, SocketError, URI::InvalidURIError false end } !url.nil? && !url.empty? && (Net::HTTPSuccess === res.call(url) || Net::HTTPRedirection === res.call(url)) end
https 対応版(2017/1/17追記)
require 'net/http' def url_exist?(url) res = ->(url) { begin uri = URI.parse(url) uri_path = uri.path.empty? ? "/" : uri.path Net::HTTP.start(uri.host, uri.port, use_ssl: (uri.scheme == 'https')) { |http| http.get(uri_path) } rescue TypeError, SocketError, URI::InvalidURIError false end } !url.nil? && !url.empty? && (Net::HTTPSuccess === res.call(url) || Net::HTTPRedirection === res.call(url)) end
関連リンク:Web上の画像を付けてツイート - 別館 子子子子子子(ねこのここねこ)
参考:
参考2(https対応):
If you set
:use_ssl
astrue
, you can use https and default value ofverify_mode
is set asOpenSSL::SSL::VERIFY_PEER
.