首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用rails运行HTTP请求

使用rails运行HTTP请求
EN

Stack Overflow用户
提问于 2014-11-05 23:49:15
回答 2查看 1.2K关注 0票数 0

我好久没用过Rails了。我现在有一个卷曲请求,如下所示

代码语言:javascript
复制
curl -X GET -H 'Authorization: Element TOKEN, User TOKEN' 'https://api.cloud-elements.com/elements/api-v2/hubs/marketing/ping' 

我所要做的就是能够在rails控制器内部运行这个请求,但对于HTTP请求,我缺乏理解,这使我无法理解如何最好地处理这个请求。提前谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-11-06 00:08:44

对于HTTP请求,请使用此方法:

代码语言:javascript
复制
  def api_request(type , url, body=nil, header =nil )
    require "net/http"
    uri = URI.parse(url)
    case type
    when :post
      request = Net::HTTP::Post.new(uri)
      request.body = body
    when :get
      request = Net::HTTP::Get.new(uri)
    when :put
      request = Net::HTTP::Put.new(uri)
      request.body = body
    when :delete
      request = Net::HTTP::Delete.new(uri)
    end
    request.initialize_http_header(header)
    #request.content_type = 'application/json'
    response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http| http.request request}
  end

你的例子是:

代码语言:javascript
复制
api_request(:get, "https://api.cloud-elements.com/elements/api-v2/hubs/marketing/ping",nil, {"Authorization" => "Element TOKEN, User TOKEN" })
票数 3
EN

Stack Overflow用户

发布于 2014-11-06 00:19:17

它将类似于下面的内容。请注意,连接将被阻塞,因此它可以根据远程主机返回HTTP响应的速度和发出的请求数量来绑定服务器。

代码语言:javascript
复制
require 'net/http'

# Let Ruby form a canonical URI from our URL
ping_uri = URI('https://api.cloud-elements.com/elements/api-v2/hubs/marketing/ping')

# Pass the basic configuration to Net::HTTP
# Note, this is not asynchronous. Ruby will wait until the HTTP connection
# has closed before moving forward
Net::HTTP.start(ping_uri.host, ping_uri.port, :use_ssl => true) do |http|
  # Build the request using the URI as a Net::HTTP::Get object
  request = Net::HTTP::Get.new(ping_uri)
  # Add the Authorization header
  request['Authorization'] = "Element #{ELEMENT_TOKEN}, User #{user.token}"

  # Actually send the request
  response = http.request(request)
  # Ruby will automatically close the connection once we exit the block
end

一旦块退出,您就可以根据需要使用response对象。response对象始终是Net::HTTPResponse的子类(或子类的子类),您可以使用response.is_a? Net::HTTPSuccess来检查2xx响应。响应的实际主体将以字符串形式在response.body中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26769347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档