Mark Szymanski
Mark Szymanski

Reputation: 58170

Making a URL in a string usable by Ruby's Net::HTTP

Ruby's Net:HTTP needs to be given a full URL in order for it to connect to the server and get the file properly. By "full URL" I mean a URL including the http:// part and the trailing slash if it needs it. For instance, Net:HTTP won't connect to a URL looking like this: example.com, but will connect just fine to http://example.com/. Is there any way to make sure a URL is a full URL, and add the required parts if it isn't?

EDIT: Here is the code I am using:

parsed_url = URI.parse(url)
req = Net::HTTP::Get.new(parsed_url.path)
res = Net::HTTP.start(parsed_url.host, parsed_url.port) {|http|
  http.request(req)
}

Upvotes: 1

Views: 2018

Answers (2)

the Tin Man
the Tin Man

Reputation: 160631

If this is only doing what the sample code shows, Open-URI would be an easier approach.

require 'open-uri'
res = open(url).read

Upvotes: 3

Dylan Markow
Dylan Markow

Reputation: 124479

This would do a simple check for http/https:

if !(url =~ /^https?:/i)
  url = "http://" + url
end

This could be a more general one to handle multiple protocols (ftp, etc.)

if !(url =~ /^\w:/i)
  url = "http://" + url
end

In order to make sure parsed_url.path gives you a proper value (it should be / when no specific path was provided), you could do something like this:

req = Net::HTTP::Get.new(parsed_url.path.empty? ? '/' : parsed_url.path)

Upvotes: 1

Related Questions