Friday, August 13, 2010

HTTP GET and POST requests with Ruby

Here is the method I needed to add the POST request to:
01def email_to_friend
02  ...other code...
03  # now, do the dirty work
04  require 'net/http'
05  # get the url that we need to post to
06  url = URI.parse('http://www.url.com/subscribe')
07  # build the params string
08  post_args1 = { 'email' => params[:email] }
09  # send the request
10  resp, data = Net::HTTP.post_form(url, post_args1)
The post_form method returns a Net::HTTPResponse object and an entity body string (in Ruby 1.8, it only returns the Net::HTTPResponse object). You can also use the post method.
Similarly, you can perform a GET request on a URL like so:
1require 'net/http'
2result = Net::HTTP.get(URI.parse('http://www.site.com/about.html'))
3# or
4result = Net::HTTP.get(URI.parse('http://www.site.com'), '/about.html')
The get method returns a String.
That's simple enough, right?


Post a Comment

Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Macys Printable Coupons