From 88243c5303ec5db2a58e355dd494b63f85b85558 Mon Sep 17 00:00:00 2001 From: shugo Date: Sat, 5 Nov 2016 14:39:06 +0000 Subject: [PATCH] * lib/net/http.rb (Net::HTTP.post): new convenience method to send a POST request. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@56597 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ChangeLog | 5 +++++ NEWS | 3 +++ lib/net/http.rb | 18 ++++++++++++++++++ test/net/http/test_http.rb | 16 ++++++++++++++++ 4 files changed, 42 insertions(+) diff --git a/ChangeLog b/ChangeLog index d305370b6c..f445e829e1 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +Sat Nov 5 23:30:41 2016 Shugo Maeda + + * lib/net/http.rb (Net::HTTP.post): new convenience method to send + a POST request. + Sat Nov 5 23:03:54 2016 NARUSE, Yui * lib/net/http.rb (transport_request): other than HTTPContinue diff --git a/NEWS b/NEWS index 806dc28fb4..64eb99e8b0 100644 --- a/NEWS +++ b/NEWS @@ -217,6 +217,9 @@ with all sufficient information, see the ChangeLog file or Redmine * Don't allow , as a separator [Bug #12791] +* Net::HTTP + * New method: Net::HTTP.post [Feature #12375] + === Compatibility issues (excluding feature bug fixes) * Array#sum and Enumerable#sum are implemented. [Feature #12217] diff --git a/lib/net/http.rb b/lib/net/http.rb index 6031bcaaeb..d68d2c740e 100644 --- a/lib/net/http.rb +++ b/lib/net/http.rb @@ -489,6 +489,24 @@ module Net #:nodoc: end end + # Posts data to the specified URI object. + # + # Example: + # + # require 'net/http' + # require 'uri' + # + # Net::HTTP.post URI('http://www.example.com/api/search'), + # { "q" => "ruby", "max" => "50" }.to_json, + # "Content-Type" => "application/json" + # + def HTTP.post(url, data, header = nil) + start(url.hostname, url.port, + :use_ssl => url.scheme == 'https' ) {|http| + http.post(url.path, data, header) + } + end + # Posts HTML form data to the specified URI object. # The form data must be provided as a Hash mapping from String to String. # Example: diff --git a/test/net/http/test_http.rb b/test/net/http/test_http.rb index 9dd665c530..f2c03f2915 100644 --- a/test/net/http/test_http.rb +++ b/test/net/http/test_http.rb @@ -384,6 +384,22 @@ module TestNetHTTP_version_1_1_methods end end + def test_s_post + url = "http://#{config('host')}:#{config('port')}/" + res = Net::HTTP.post( + URI.parse(url), + "a=x") + assert_equal "application/x-www-form-urlencoded", res["Content-Type"] + assert_equal "a=x", res.body + + res = Net::HTTP.post( + URI.parse(url), + "hello world", + "Content-Type" => "text/plain; charset=US-ASCII") + assert_equal "text/plain; charset=US-ASCII", res["Content-Type"] + assert_equal "hello world", res.body + end + def test_s_post_form url = "http://#{config('host')}:#{config('port')}/" res = Net::HTTP.post_form(