User submits a form with some basic data.
The data is received and treated by an action in the controller and more information that needs to remain private is added.
Then I need to send a post request to an external website with all of the combined data from the controller.
What is the best way to do this?
The simpliest way is using ruby core library:
require "uri"
require "net/http"
params = {'box1' => 'Nothing is less important than which fork you use. Etiquette is the science of living. It embraces everything. It is ethics. It is honor. -Emily Post',
'button1' => 'Submit'
}
x = Net::HTTP.post_form(URI.parse('http://www.interlacken.com/webdbdev/ch05/formpost.asp'), params)
puts x.body
Pro Tip: Do an asynchronous request, using a gem like delayed_job or background_rb
Sorry, I neglected to mention that I was connecting to secure server. This seems to have been the reason that I was getting end of file errors. Adding using 'net/https' and calling use_ssl on connection solved the problem. Thanks for everyones help.
require 'net/https'
require 'open-uri'
url = URI.parse('https://MY_URL')
req = Net::HTTP::Post.new(url.path)
req.form_data = data
req.basic_auth url.user, url.password if url.user
con = Net::HTTP.new(url.host, url.port)
con.use_ssl = true
con.start {|http| http.request(req)}
This is based off the source for the post_form method, so i guess I'll give vlad.zloteanu the answer.
If the external server is RESTful, then simply create an ActiveResource model to handle your data.
I don't think redirect_to handles post requests because it uses http 302 (?) which just GETs the other page.
I believe you can do something like this
Class MyController < ActionController
require 'net/http'
def my_method
#do something with the data/model
my_connection = Net::HTTP.new('www.target.com', 80)
reponse = my_connection.post(path_within_url, data)
#do something with response if you want
end
end
note: this is air coded and has not been tried or tested
If you want to send JSON, all you need is something like the following (tested in Rails 6):
Net::HTTP.post(
URI('https://example.com/some/path'),
{ "this is the": "request body" }.to_json,
'Content-Type' => 'application/json'
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With