Skip to content

Commit b8c06e3

Browse files
committed
Net::HTTP.get_response can receive URI as string
1 parent 9b2d818 commit b8c06e3

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

lib/net/http.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -796,6 +796,12 @@ def HTTP.get_print(uri_or_host, path_or_headers = nil, port = nil)
796796
# headers = {'Content-type' => 'application/json; charset=UTF-8'}
797797
# Net::HTTP.get(uri, headers)
798798
#
799+
# Alternatively, +uri+ may be a String:
800+
#
801+
# uri = 'https://jsonplaceholder.typicode.com/todos/1'
802+
# headers = {'Content-type' => 'application/json; charset=UTF-8'}
803+
# Net::HTTP.get(uri, headers)
804+
#
799805
# Related:
800806
#
801807
# - Net::HTTP::Get: request class for \HTTP method +GET+.
@@ -820,6 +826,7 @@ def HTTP.get_response(uri_or_host, path_or_headers = nil, port = nil, &block)
820826
}
821827
else
822828
uri = uri_or_host
829+
uri = URI(uri) if uri.is_a?(String)
823830
headers = path_or_headers
824831
start(uri.hostname, uri.port,
825832
:use_ssl => uri.scheme == 'https') {|http|

test/net/http/test_http.rb

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,13 @@ def test_s_get
303303
assert_equal $test_net_http_data,
304304
Net::HTTP.get(config('host'), '/', config('port'))
305305

306+
assert_equal $test_net_http_data,
307+
Net::HTTP.get("http://#{config('host')}:#{config('port')}")
308+
309+
assert_equal $test_net_http_data, Net::HTTP.get(
310+
"http://#{config('host')}:#{config('port')}", "Accept" => "text/plain"
311+
)
312+
306313
assert_equal $test_net_http_data, Net::HTTP.get(
307314
URI.parse("http://#{config('host')}:#{config('port')}")
308315
)
@@ -311,7 +318,23 @@ def test_s_get
311318
)
312319
end
313320

314-
def test_s_get_response
321+
def test_s_get_response_with_host
322+
res = Net::HTTP.get_response(config('host'), '/', config('port'))
323+
assert_equal "application/octet-stream", res["Content-Type"]
324+
assert_equal $test_net_http_data, res.body
325+
end
326+
327+
def test_s_get_response_with_uri_string
328+
res = Net::HTTP.get_response("http://#{config('host')}:#{config('port')}")
329+
assert_equal "application/octet-stream", res["Content-Type"]
330+
assert_equal $test_net_http_data, res.body
331+
332+
res = Net::HTTP.get_response("http://#{config('host')}:#{config('port')}", "Accept" => "text/plain")
333+
assert_equal "text/plain", res["Content-Type"]
334+
assert_equal $test_net_http_data, res.body
335+
end
336+
337+
def test_s_get_response_with_uri
315338
res = Net::HTTP.get_response(
316339
URI.parse("http://#{config('host')}:#{config('port')}")
317340
)

0 commit comments

Comments
 (0)