web-dev-qa-db-ja.com

POSTコントローラから別のWebサイトへのデータRails

  1. ユーザーがいくつかの基本データを含むフォームを送信します。

  2. データはコントローラー内のアクションによって受信および処理され、非公開のままにする必要がある情報が追加されます。

  3. 次に、コントローラーからのすべての結合データを含む外部Webサイトに投稿要求を送信する必要があります。

これを行う最良の方法は何ですか?

48
Alex.Bullard

最も簡単な方法は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

プロのヒント: delayed_job またはbackground_rbのようなgemを使用して、非同期リクエストを実行します

82
Vlad Zloteanu

申し訳ありませんが、セキュリティで保護されたサーバーに接続していたことをお伝えできませんでした。これが、ファイルの終わりエラーを取得していた理由のようです。 「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に答えを与えると思います。

33
Alex.Bullard

外部サーバーがRESTfulである場合、データを処理するために ActiveResource モデルを作成するだけです。

12
askegg

他のページを取得するだけのhttp 302(?)を使用するため、redirect_toが投稿要求を処理するとは思わない。

このようなことができると思います

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

注:これはエアコーディングされており、試行またはテストされていません

4
ErsatzRyan