From 2b3d2ddb37d084e5188c804150f3587c721abe20 Mon Sep 17 00:00:00 2001 From: Yusuke Endoh Date: Wed, 8 Oct 2025 14:40:01 +0900 Subject: [PATCH] Allow a URL String for shorthand methods In short, this allows `Net::HTTP.get("http://example.com")` instead of `Net::HTTP.get(URI("http://example.com"))`. --- lib/net/http.rb | 9 ++++++--- test/net/http/test_http.rb | 13 +++++-------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/lib/net/http.rb b/lib/net/http.rb index f64f7ba..1a1aa20 100644 --- a/lib/net/http.rb +++ b/lib/net/http.rb @@ -819,7 +819,7 @@ def HTTP.get_response(uri_or_host, path_or_headers = nil, port = nil, &block) return http.request_get(path, &block) } else - uri = uri_or_host + uri = URI(uri_or_host) headers = path_or_headers start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') {|http| @@ -830,7 +830,7 @@ def HTTP.get_response(uri_or_host, path_or_headers = nil, port = nil, &block) # Posts data to a host; returns a Net::HTTPResponse object. # - # Argument +url+ must be a URL; + # Argument +url+ must be a URI; # argument +data+ must be a string: # # _uri = uri.dup @@ -855,6 +855,7 @@ def HTTP.get_response(uri_or_host, path_or_headers = nil, port = nil, &block) # - Net::HTTP#post: convenience method for \HTTP method +POST+. # def HTTP.post(url, data, header = nil) + url = URI(url) start(url.hostname, url.port, :use_ssl => url.scheme == 'https' ) {|http| http.post(url, data, header) @@ -882,6 +883,7 @@ def HTTP.post(url, data, header = nil) # } # def HTTP.post_form(url, params) + url = URI(url) req = Post.new(url) req.form_data = params req.basic_auth url.user, url.password if url.user @@ -893,7 +895,7 @@ def HTTP.post_form(url, params) # Sends a PUT request to the server; returns a Net::HTTPResponse object. # - # Argument +url+ must be a URL; + # Argument +url+ must be a URI; # argument +data+ must be a string: # # _uri = uri.dup @@ -918,6 +920,7 @@ def HTTP.post_form(url, params) # - Net::HTTP#put: convenience method for \HTTP method +PUT+. # def HTTP.put(url, data, header = nil) + url = URI(url) start(url.hostname, url.port, :use_ssl => url.scheme == 'https' ) {|http| http.put(url, data, header) diff --git a/test/net/http/test_http.rb b/test/net/http/test_http.rb index 366b4cd..cc06e8d 100644 --- a/test/net/http/test_http.rb +++ b/test/net/http/test_http.rb @@ -243,14 +243,11 @@ def test_newobj end def test_failure_message_includes_failed_domain_and_port - # hostname to be included in the error message - host = Struct.new(:to_s).new("") - port = 2119 - # hack to let TCPSocket.open fail - def host.to_str; raise SocketError, "open failure"; end - uri = Struct.new(:scheme, :hostname, :port).new("http", host, port) - assert_raise_with_message(SocketError, /#{host}:#{port}/) do - TestNetHTTPUtils.clean_http_proxy_env{ Net::HTTP.get(uri) } + begin + Net::HTTP.get(URI.parse("http://example.invalid")) + fail "should have raised" + rescue => e + assert_includes e.message, "example.invalid:80" end end