用戶使用一些基本數據提交表單。從控制器向Rails中的另一個網站提交POST數據
通過控制器中的操作接收和處理數據,並添加需要保持私密的更多信息。
然後,我需要發送一個帖子請求到外部網站與控制器的所有組合數據。
這樣做的最好方法是什麼?
用戶使用一些基本數據提交表單。從控制器向Rails中的另一個網站提交POST數據
通過控制器中的操作接收和處理數據,並添加需要保持私密的更多信息。
然後,我需要發送一個帖子請求到外部網站與控制器的所有組合數據。
這樣做的最好方法是什麼?
的simpliest方法是使用紅寶石核心庫:
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
專業提示:使用諸如delayed_job或background_rb的寶石執行異步請求
取自:http://biodegradablegeek.com/2008/04/how-to-post-form-data-using-ruby/
我不認爲redirect_to處理髮布請求,因爲它使用http 302(?),它只是獲取其他頁面。
我相信你可以做這樣的事情
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
注:這是空氣編碼,並沒有被嘗試過或測試
對不起,我忽略提及我正在連接到安全服務器。這似乎是我得到文件錯誤結束的原因。使用'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)}
這是基於post_form方法的源代碼,所以我想我會給vlad.zloteanu的答案。
如果外部服務器是RESTful的,那麼只需創建一個ActiveResource模型來處理您的數據。
在Ryan的railscast上使用delayed_job的例子:http://railscasts.com/episodes/171-delayed-job – 2009-07-28 19:12:07
這是我嘗試的第一件事。不幸的是,它給了我一個'達到文件結束'的錯誤。從四處搜尋看來,其他人也有類似的問題。任何人有任何見解? – 2009-07-28 19:41:20