开发者

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 connec开发者_Go百科t 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)
}


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

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


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)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜