从Ruby on Rails控制器调用外部API

时间:2017-11-19 12:34:32

标签: ruby-on-rails ruby

我在使用Ruby on Rails控制器调用外部API时遇到了困难

以下代码是我的目的地控制器

url = URI.parse("https://api.sygictravelapi.com/1.0/en/places/list?parents=#{@destination.destination_type.downcase}:#{@destination.sygia_id}&level=poi")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true


req = Net::HTTP::Get.new(url.to_s)
req.add_field 'x-api-key', ENV["SYGIC_API_KEY"]

res = Net::HTTP.start(url.host, url.port) {
   |http|
   http.request(req)
}

问题在于,当我发出此请求时,响应是“错误请求”,没有任何进一步的信息。通过Postman使用完全相同的请求标头和URL,我从端点获得200-OK响应,以及我期望的数据。

使用Wireshark监控流量时,我看到一个HTTP请求进入API端点。但是在使用Postman时,我只看到了TLS请求。

我也尝试过对Query String参数的不同编码无济于事。我的假设是导致问题的是这两件事之一:1)SSL未被使用2)QueryString参数未附加到HTTP请求。但是我想在我的代码上额外注意检查一下,我并没有错过任何明显的东西。

1 个答案:

答案 0 :(得分:0)

Rest-Client Ruby Gem: Help creating get request with Headers, Query, and setting a proxy

问题原来并不是我,而是我正在使用的搜索引擎。因为我住在中国,所以我必须求助于Bing(出于性能原因)...但是连接到VPN,并且通过1 Google搜索,我可以找到上面的链接。

以下代码将解决问题

body = RestClient.get "https://api.sygictravelapi.com/1.0/en/places/list?parents=#{@destination.destination_type.downcase}:#{@destination.sygia_id}&level=poi",
      headers = {accept: :json,  'x-api-key' => ENV["SYGIC_API_KEY"]}

如果您不想安装新的gem,上面的正确代码基于Postman的有用代码生成功能:

require 'uri'
require 'net/http'

url = URI("https://api.sygictravelapi.com/1.0/en/places/list?parents=city%3A372&level=poi&limit=100")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Get.new(url)
request["x-api-key"] = ENV["SYGIC_API_KEY"]
request["cache-control"] = 'no-cache'

response = http.request(request)
puts response.read_body