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

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

  3. 次に、コントローラーからのすべての結合データを使用して、POSTリクエストを外部のWebサイトに送信する必要があります。

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

4

5 に答える 5

86

最も簡単な方法は、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 を使用して、非同期リクエストを実行します。

于 2009-07-28T19:10:11.323 に答える
33

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

于 2009-07-29T15:52:48.823 に答える
13

外部サーバーが RESTful の場合は、ActiveResourceモデルを作成してデータを処理します。

于 2009-07-30T12:43:38.347 に答える
4

他のページを取得するだけの 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

注:これはエアコードであり、試行もテストもされていません

于 2009-07-28T19:06:21.673 に答える
0

JSON を送信する場合、必要なのは次のようなものだけです (Rails 6 でテスト済み)。

Net::HTTP.post(
  URI('https://example.com/some/path'),
  { "this is the": "request body" }.to_json,
  'Content-Type' => 'application/json'
)
于 2020-06-03T03:32:02.710 に答える