在Ruby中通过SSL进行API调用

时间:2013-12-20 18:51:57

标签: ruby-on-rails ruby api ssl

我有一个方法可以很好地调用非ssl apis,但每当我请求https-only apis时它会给我以下错误响应:

757: unexpected token at '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
Reason: You're speaking plain HTTP to an SSL-enabled server port.<br />
 Instead use the HTTPS scheme to access this URL, please.<br />
</p>
</body></html>

该方法相当简单:

def my_service_api_call(path = nil, query = nil)
  my_service_api_key = ENV["MY_SERVICE_KEY"]
  api_path = "#{path}/?api_key=#{my_service_api_key}&#{query}"
  url = URI.parse(api_path)
  req = Net::HTTP::Get.new(api_path)
  res = Net::HTTP.start(url.host, url.port) { |http| http.request(req) }
  JSON.parse(res.body)["results"]
end

这比http更好用,但是只能通过https进行故障转移。是否有相同的方式来进行HTTPS请求?

2 个答案:

答案 0 :(得分:6)

通过HTTPS重用您的Net::HTTP 启用请求的实例有一种更优雅的方式:

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE # Sets the HTTPS verify mode
@data = http.get(uri.request_uri) 

请注意use_ssl的使用。来自the documentation

  

打开/关闭SSL。必须在开始会话之前设置此标志。如果在会话启动后更改use_ssl值,则Net :: HTTP对象会引发IOError。

另请注意VERIFY_NONE的使用是有争议的,因为it doesn't force the validity of of certificates to be checked。对于许多应用程序和用户,这不会带来任何负面影响。如果要检查证书有效期 this post建议如下:

  

安全地传输正确的证书并更新默认证书存储区或设置ca文件。

答案 1 :(得分:1)

您需要将use_ssl设置为true:

像这样:

        http = Net::HTTP.new(uri.hostname, uri.port)
        http.use_ssl = true
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE
        http.ssl_version = :SSLv3