post to external form

Hi,

This is probably a dumb question but I can't figure it out.

How do you post to an external form? I think the easiest way would be to do a GET on the URL with the query arguments but I don't know how to do that in a Ruby on Rails controller. And it'd be cool to figure out if the form submitted correctly.

Thanks,

Frank,

What do you mean? You can't post TO a form, you post FROM a form...

Cheers, Sazima

I probably did not say it right. I'll try again. :slight_smile:

There is a form on another website. I want to submit data to this external from from my RoR app.

I thought a simple way would be to do a get on the URL of the form with query arguments for the different fields of the form. But I don't even know how to do that. Can anyone help?

Hi Frank,

What you need to do is a bit of http client programming. There are lots of options, including:

http://dev.ctor.org/http-access2 http://rfuzz.rubyforge.org http://curb.rubyforge.org ...

Whatever you use depends on your needs/tastes.

A simplified (non-error-checked) example of retrieving the current google stock price and change from yahoo via POST (even tho quote.csv is GET'able) using ruby's Net:HTTP (Ruby 3.1.2 Standard Library Documentation libdoc/net/http/rdoc/classes/Net/HTTP.html):

$ irb irb(main):001:0> require 'net/http' => true

irb(main):002:0> require 'uri' => false

irb(main):003:0> app_uri = URI.parse('http:// download.finance.yahoo.com/d/quotes.csv') => #<URI::HTTP:0xfdbd68e4e URL:http://download.finance.yahoo.com/d/ quotes.csv>

irb(main):004:0> params = {'s'=>'GOOG', 'f'=>'l1c1'} => {"f"=>"l1c1", "s"=>"GOOG"}

irb(main):005:0> price,change = Net::HTTP.post_form(app_uri, params).body.chomp.split(',') => ["351.10", "+8.44"]

You probably don't want to use Net::HTTP tho, given it's limitations. Personally, of the various ruby http clients I've used, I have yet to find one that I end up using more than I do just wrapping wget (http:// linux.die.net/man/1/wget), when available for use, given all of the inherent built-in goodies/flexibility provided by wget. Here's a similar simplified wget example of the above:

$ irb irb(main):001:0> require 'cgi' => true

irb(main):002:0> app_url = 'http://download.finance.yahoo.com/d/ quotes.csv' => "http://download.finance.yahoo.com/d/quotes.csv&quot;

irb(main):003:0> params = {'s'=>'GOOG', 'f'=>'l1c1'} => {"f"=>"l1c1", "s"=>"GOOG"}

irb(main):004:0> postable_params = params.to_a.collect {|k,v| "# {CGI::escape(k)}=#{CGI::escape(v)}" }.join('&') => "f=l1c1&s=GOOG"

irb(main):005:0> price,change = `wget -o /dev/null -T 2.0 --post-data '#{postable_params}' -O - '#{app_url}'`.chomp.split(',') => ["349.80", "+7.14"]

Jeff

Thanks. That's really helpful, I'll try it out.