POST a form in Ruby

By: Emiley J.  

This sample code is used to post a form data to an URL.

require 'net/http'
    require 'uri'

    #1: Simple POST
    res = Net::HTTP.post_form(URI.parse(''),
                              {'q'=>'ruby', 'max'=>'50'})
    puts res.body

    #2: POST with basic authentication
    res = Net::HTTP.post_form(URI.parse('http://jack:[email protected]/todo.cgi'),
                                        {'from'=>'2005-01-01', 'to'=>'2005-03-31'})
    puts res.body

    #3: Detailed control
    url = URI.parse('')
    req =
    req.basic_auth 'jack', 'pass'
    req.set_form_data({'from'=>'2005-01-01', 'to'=>'2005-03-31'}, ';')
    res =, url.port).start { http.request(req) }
    case res
    when Net::HTTPSuccess, Net::HTTPRedirection
      # OK

Archived Comments

Most Viewed Articles (in Ruby )

Latest Articles (in Ruby)

Comment on this tutorial