diff --git a/lib/bio/command.rb b/lib/bio/command.rb index bcf022fbf..97d85d6ab 100644 --- a/lib/bio/command.rb +++ b/lib/bio/command.rb @@ -13,6 +13,7 @@ require 'open-uri' require 'cgi' require 'net/http' +require 'net/https' require 'tmpdir' require 'fileutils' @@ -706,6 +707,43 @@ def read_uri(uri) OpenURI.open_uri(uri).read end + # Same as: + # Net::HTTP.start(uri.address, uri.port) + # and + # it uses proxy if an environment variable (same as OpenURI.open_uri) + # is set. + # It supports https. + # + # Note: This method ignores uri.path. + # It only uses uri.address and uri.port. + # + # --- + # *Arguments*: + # * (required) _uri_: URI object or String containing URI + # *Returns*:: (same as Net::HTTP::start except for proxy and https support) + def start_http_uri(uri, &block) + unless uri.is_a?(URI) + uri = URI.parse(uri) + end + + # Note: URI#find_proxy is an unofficial method defined in open-uri.rb. + # If the spec of open-uri.rb would be changed, we should change below. + if proxyuri = uri.find_proxy then + raise 'Non-HTTP proxy' if proxyuri.class != URI::HTTP + klass = Net::HTTP.Proxy(proxyuri.host, proxyuri.port) + else + klass = Net::HTTP + end + + http = klass.new(uri.host, uri.port) + case uri.scheme + when 'https' + http.use_ssl = true + end + + http.start(&block) + end + # Same as: # Net::HTTP.start(address, port) # and @@ -813,7 +851,7 @@ def post_form(uri, params = nil, header = {}) } hash.update(header) - start_http(uri.host, uri.port) do |http| + start_http_uri(uri) do |http| http.post(uri.path, data, hash) end end @@ -937,7 +975,7 @@ def post(uri, data, header = {}) } hash.update(header) - start_http(uri.host, uri.port) do |http| + start_http_uri(uri) do |http| http.post(uri.path, data, hash) end end diff --git a/test/network/bio/test_command.rb b/test/network/bio/test_command.rb index 815d96fa7..8ade322af 100644 --- a/test/network/bio/test_command.rb +++ b/test/network/bio/test_command.rb @@ -13,6 +13,7 @@ # libraries needed for the tests require 'test/unit' +require 'uri' require 'bio/command' module Bio @@ -22,6 +23,7 @@ def setup @port = 80 @path = "/" @url = "http://bioruby.open-bio.org:80/" + @uri = URI.parse(@url) end def test_read_uri @@ -32,6 +34,21 @@ def test_read_uri assert(!str.to_s.empty?) end + def test_start_http_uri + ht = Bio::Command.start_http_uri(@uri) + assert_kind_of(Net::HTTP, ht) + res = ht.get(@path) + assert_kind_of(Net::HTTPResponse, res) + end + + def test_start_http_uri_with_block + res = Bio::Command.start_http_uri(@uri) do |ht| + assert_kind_of(Net::HTTP, ht) + ht.get(@path) + end + assert_kind_of(Net::HTTPResponse, res) + end + def test_start_http ht = Bio::Command.start_http(@host, @port) assert_kind_of(Net::HTTP, ht)