Skip to content

Instantly share code, notes, and snippets.

@rm3l
Forked from kinopyo/ruby_http_post.rb
Created January 20, 2020 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rm3l/eaf682d4c89931f0f64b459a0ecfcbbf to your computer and use it in GitHub Desktop.
Save rm3l/eaf682d4c89931f0f64b459a0ecfcbbf to your computer and use it in GitHub Desktop.
Pure ruby code posting form data with parameters, and get the response.
require 'net/http'
require 'uri'
#1: Simple POST
res = Net::HTTP.post_form(URI.parse('http://www.example.com/search.cgi'),
{'q' => 'ruby', 'max' => '50'})
puts res.body
#2: POST with basic authentication
res = Net::HTTP.post_form(URI.parse('http://jack:pass@www.example.com/todo.cgi'),
{'from' => '2005-01-01',
'to' => '2005-03-31'})
puts res.body
#3: Detailed control
url = URI.parse('http://www.example.com/todo.cgi')
req = Net::HTTP::Post.new(url.path)
req.basic_auth 'jack', 'pass'
req.set_form_data({'from' => '2005-01-01', 'to' => '2005-03-31'}, ';')
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
case res
when Net::HTTPSuccess, Net::HTTPRedirection
# OK
else
res.error!
end
#4: Multiple values
res = Net::HTTP.post_form(URI.parse('http://www.example.com/search.cgi'),
{'q' => ['ruby', 'perl'], 'max' => '50'})
puts res.body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment