【问题标题】:Get HTTP POST Response in Rails Controler在 Rails 控制器中获取 HTTP POST 响应
【发布时间】:2014-11-03 14:18:03
【问题描述】:

我有两个 Rails 应用程序。 App #1 从一个控制器动作向 App #2 中的另一个控制器动作发送一个 post 请求。我希望能够在 App #1 中读取对该 POST 的响应。

App #1 控制器:

  require 'net/http'
  # get the url that we need to post to
  url = URI.parse('http://app2.com/sessions/login_request')
  # build the params string
  post_args1 = { 
    'username' => 'my@test.com' 
  }
  # send the request
  resp, data = Net::HTTP.post_form(url, post_args1)

  #HOW do I read :token and :tokenMnemonic here??

应用 #2 控制器:

def login_request
  # do some logic here
  render :json => {
    :result => "OK",
    :token => random_token,
    :tokenMnemonic => tokenMnemonic
  }
end

问题是我如何从 App #1 的控制器收到的 POST 响应中读取 :token 和 :tokenMnemonic。

【问题讨论】:

    标签: ruby-on-rails http post


    【解决方案1】:

    变量resp 代表响应对象。您可以使用#body 方法将响应的正文作为字符串获取。

    如果正文是 JSON 的 String 序列化,只需将其解析回以获取元素。

    hash = JSON.parse(resp.body)
    hash['token']
    # => ...
    

    【讨论】:

    • 是的!有用!我认为这是一个同步 POST,对吧?
    • Simone,很抱歉这样与您联系,但我不知道如何与您取得联系。我注意到您投票决定将我的问题 stackoverflow.com/questions/26743387/… 搁置。它现在已经被编辑得更清楚了,我急需一个答案。请考虑撤回您的投票,以便我尽快悬赏。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    相关资源
    最近更新 更多