Reputation: 75
Suppose that after primitive validation of user submitted URL I have the string that looks like URL:
url = 'http://www.thisdomaindoesntexist.com/dont_even_ask_about/this/uri'
How can I check if its available or not?
I tried this in my is_valid_link function:
require "net/http"
url = URI.parse(url)
req = Net::HTTP.new(url.host, url.port)
res = req.request_head(url.path)
It works if the server exists giving me back the HTTP response, but the problem is that in case of bad url I get an error like this:
SocketError in PostsController#create
getaddrinfo: nodename nor servname provided, or not known
How should I do this kind of validation properly?
Thanks in advance.
Upvotes: 0
Views: 1558
Reputation: 25
I've looked for a way to check if URL existed for 5 hours and this thread actually helped me. I'm a newbie in rails and wanted to find something easy.
Here how I integrated the code into controller:
require "net/http"
def url
url = URI.parse('http://www.url that you want to check.com/' + "/")
end
def req
@req = Net::HTTP.new(url.host, url.port)
end
def res #res
@res = req.request_head(url.path)
rescue
false
end
def test
if res == false
"something"
else
"another thing"
end
you have to make sure that URL ends with "/", else the code won't work.
Upvotes: 0
Reputation: 6241
You can use rescue
to catch errors and do some error handling
begin
require "net/http"
url = URI.parse(url)
req = Net::HTTP.new(url.host, url.port)
res = req.request_head(url.path)
rescue
# error occured, return false
false
else
# valid site
true
end
Use rescue
inline:
require "net/http"
url = URI.parse(url)
req = Net::HTTP.new(url.host, url.port)
res = req.request_head(url.path) rescue false
Upvotes: 4