我好久没用过Rails了。我现在有一个卷曲请求,如下所示
curl -X GET -H 'Authorization: Element TOKEN, User TOKEN' 'https://api.cloud-elements.com/elements/api-v2/hubs/marketing/ping' 我所要做的就是能够在rails控制器内部运行这个请求,但对于HTTP请求,我缺乏理解,这使我无法理解如何最好地处理这个请求。提前谢谢。
发布于 2014-11-06 00:08:44
对于HTTP请求,请使用此方法:
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你的例子是:
api_request(:get, "https://api.cloud-elements.com/elements/api-v2/hubs/marketing/ping",nil, {"Authorization" => "Element TOKEN, User TOKEN" })发布于 2014-11-06 00:19:17
它将类似于下面的内容。请注意,连接将被阻塞,因此它可以根据远程主机返回HTTP响应的速度和发出的请求数量来绑定服务器。
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中。
https://stackoverflow.com/questions/26769347
复制相似问题