【问题标题】:Submit POST data from controller to another website in Rails将 POST 数据从控制器提交到 Rails 中的另一个网站
【发布时间】:2009-07-28 18:40:00
【问题描述】:
  1. 用户提交包含一些基本数据的表单。

  2. 通过控制器中的操作接收和处理数据,并添加更多需要保密的信息。

  3. 然后我需要向外部网站发送一个发布请求,其中包含来自控制器的所有组合数据。

最好的方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby forms request form-submit


    【解决方案1】:

    最简单的方法是使用 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 执行异步请求

    【讨论】:

    • 在 Ryan 的 railscast 上使用delayed_job 的示例:railscasts.com/episodes/171-delayed-job
    • 这是我尝试的第一件事。不幸的是,它给了我一个“到达文件结尾”的错误。从周围搜索看来,其他人也有类似的问题。有人有什么见解吗?
    • 解决使用https时出现EOF错误,见stackoverflow.com/a/9227933/1161743
    • @VladZloteanu - 为什么你的建议是“做一个异步请求,使用像delayed_job这样的gem”?谢谢
    【解决方案2】:

    抱歉,我没有提到我正在连接到安全服务器。这似乎是我收到文件结束错误的原因。添加 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 答案。

    【讨论】:

    • :) 好吧.. 10qu,很高兴它对你有所帮助。
    • 这似乎工作得很好,但是我希望控制器也跟随重定向到帖子,但似乎不是这样?知道我该怎么做吗?
    • 我刚刚解决的问题...将最后一行设置为响应 res = con.start {|http| http.request(req)} 很有用。
    【解决方案3】:

    如果外部服务器是 RESTful,那么只需创建一个 ActiveResource 模型来处理您的数据。

    【讨论】:

      【解决方案4】:

      我不认为redirect_to 处理post 请求,因为它使用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
      

      注意:这是空气编码的,尚未经过尝试或测试

      【讨论】:

        【解决方案5】:

        如果你想发送 JSON,你只需要类似下面的东西(在 Rails 6 中测试过):

        Net::HTTP.post(
          URI('https://example.com/some/path'),
          { "this is the": "request body" }.to_json,
          'Content-Type' => 'application/json'
        )
        

        【讨论】:

          猜你喜欢
          • 2012-12-31
          • 2021-10-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多