HTTP GET and POST requests with Ruby
NOV
07
2007
A while ago, I was working on a project for a client that used a third-party newsletter generator for capturing and storing email addresses. To add an email address, the application spits out some code for a form that you can put on your site. A user supplies his name and email address, then submits the form and it gets stored within the third-party app's database.
The problem arose when they wanted to automatically subscribe not only people who requested subscriptions, but also everyone who used the online contact form AND anyone who used the 'email to a friend' feature on one of the interior pages. Obvious misgivings aside, I set out to do what I was told (like any good drone).
The problem was, I needed to do a POST request to subscribe the person to the third-party app, but I couldn't do that with a regular form because I was already posting to the actual action being invoked. Luckily, Ruby has a built in Net::HTTP class for generating GET and POST requests from within the code.
Here is the method I needed to add the POST request to:
def email_to_friend
...other code...
# now, do the dirty work
require 'net/http'
# get the url that we need to post to
url = URI.parse('http://www.url.com/subscribe')
# build the params string
post_args1 = { 'email' => params[:email] }
# send the request
resp, data = Net::HTTP.post_form(url, post_args1)
end
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:
require 'net/http'
result = Net::HTTP.get(URI.parse('http://www.site.com/about.html'))
# or
result = Net::HTTP.get(URI.parse('http://www.site.com'), '/about.html')
The get method returns a String.
That's simple enough, right?
Tagged: rails, get, post, tutorial
Wouldn't an observer using an ActiveResource be a better solution?
@Andrew: I never claimed this was the best solution. Just presenting an option.
Leave a comment:
Popular Posts
Search
Tags
actionmailer activerecord ajax apache apple barcamp caching capistrano centos code golf css db delete eager loading ebay email attachment erb flash ftp fun generators get haml helpers ie sucks javascript jquery lightbox lost merb net ftp paperclip passenger php plexus post presentation rails rails machine railsconf redesign rest rjs routes rss ruby ruby on rails safari script sinatra symfony text replacement tips tutorial twitter xhtml
Projects
© 2010 Travis Roberts. All rights reserved.
Haris Gulzar said on January 18, 2008:
The get method returns a string, thats fine, but it returns many undesired things as well in that string. How do I parse the string that get returns. Please send a reply at harisgulzar@gmail.com