从rails控制器向另一个站点提交POST请求

时间:2013-10-10 07:07:47

标签: ruby-on-rails http-post

此问题的确切重复已超过四年here

鉴于它已经很久了,我现在的问题是,这个答案仍然准确吗?现在有更好的方法吗?

1 个答案:

答案 0 :(得分:7)

你做这样的事。在控制器中写一个函数,如下所示:

require 'net/http'
require 'net/https'
class custom_class
def get_api_call(args_hash)
    uri = URI.parse("sample_api_url")
    uri.query = URI.encode_www_form(what_args_you_want_to_send)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    request = Net::HTTP::Post.new(uri.request_uri)
    http.request(request).body
end

private

def what_args_you_want_to_send
{
      "varname1" => var1,
      "varname2" => var2,
      "varname3" => var3,
      "varname4" => var4
}
end

该功能的结果将来自您向

发送请求的服务器的答案