Running a HTTP request with rails

2019-09-09 22:05发布

It has been a while since I have used Rails. I currently have a curl request as follows

curl -X GET -H 'Authorization: Element TOKEN, User TOKEN' 'https://api.cloud-elements.com/elements/api-v2/hubs/marketing/ping' 

All I am looking to do is to be able to run this request from inside of a rails controller, but my lack of understanding when it comes to HTTP requests is preventing me from figuring it out to how best handle this. Thanks in advance.

2条回答
We Are One
2楼-- · 2019-09-09 22:40

It would be something like the following. Note that the connection will be blocking, so it can tie up your server depending on how quickly the remote host returns the HTTP response and how many of these requests you are making.

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

Once the block exits, you can use the response object as necessary. The response object is always a subclass (or subclass of a subclass) of Net::HTTPResponse and you can use response.is_a? Net::HTTPSuccess to check for a 2xx response. The actual body of the response will be in response.body as a String.

查看更多
Explosion°爆炸
3楼-- · 2019-09-09 22:43

Use this method for HTTP requests:

  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

Your example will be:

api_request(:get, "https://api.cloud-elements.com/elements/api-v2/hubs/marketing/ping",nil, {"Authorization" => "Element TOKEN, User TOKEN" })
查看更多
登录 后发表回答