Ruby-on-rails 将 POST 数据从控制器提交到 Rails 中的另一个网站
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1195962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Submit POST data from controller to another website in Rails
提问by Alex.Bullard
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?
做这个的最好方式是什么?
回答by Vlad Zloteanu
The simpliest way is using ruby core library:
最简单的方法是使用 ruby 核心库:
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_jobor background_rb
专业提示:执行异步请求,使用诸如delay_job或 background_rb 之类的 gem
回答by Alex.Bullard
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.
抱歉,我忽略了我正在连接到安全服务器。这似乎是我收到文件结尾错误的原因。添加使用 'net/https' 并在连接上调用 use_ssl 解决了该问题。谢谢大家的帮助。
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.
这是基于 post_form 方法的来源,所以我想我会给 vlad.zloteanu 答案。
回答by askegg
If the external server is RESTful, then simply create an ActiveResourcemodel to handle your data.
如果外部服务器是 RESTful,那么只需创建一个ActiveResource模型来处理您的数据。
回答by ErsatzRyan
I don't think redirect_to handles post requests because it uses http 302 (?) which just GETs the other page.
我不认为 redirect_to 处理发布请求,因为它使用 http 302 (?) 来获取其他页面。
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
注意:这是空气编码,尚未尝试或测试

