2009-07-28 37 views

回答

72

的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/

+2

在Ryan的railscast上使用delayed_job的例子:http://railscasts.com/episodes/171-delayed-job – 2009-07-28 19:12:07

+3

這是我嘗試的第一件事。不幸的是,它給了我一個'達到文件結束'的錯誤。從四處搜尋看來,其他人也有類似的問題。任何人有任何見解? – 2009-07-28 19:41:20

4

我不認爲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 

注:這是空氣編碼,並沒有被嘗試過或測試

29

對不起,我忽略提及我正在連接到安全服務器。這似乎是我得到文件錯誤結束的原因。使用'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的答案。

12

如果外部服務器是RESTful的,那麼只需創建一個ActiveResource模型來處理您的數據。

相關問題