ruby-on-rails - 在 Ruby 中通过 SSL 调用 API

标签 ruby-on-rails ruby api ssl

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

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 请求?

最佳答案

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

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 :

Turn on/off SSL. This flag must be set before starting session. If you change use_ssl value after session started, a Net::HTTP object raises IOError.

另请注意,VERIFY_NONE 的使用存在争议,因为 it doesn't force the validity of of certificates to be checked .对于许多应用程序和用户而言,这不会产生任何负面影响。如果证书有效性应该被检查,this post建议如下:

Securely transfer the correct certificate and update the default certificate store or set the ca file instead.

关于ruby-on-rails - 在 Ruby 中通过 SSL 调用 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20710170/

相关文章:

ruby-on-rails - Rails CookieStore::CookieOverflow,不适用于所有用户,仅在生产中

java - ruby on rails 项目中的 jar 文件放在哪里?

ruby - Ruby win32api 和 win32ole 有什么区别?

javascript - 引用谷歌地图中的特定位置

ruby-on-rails - 在 Heroku 应用程序中实现维护页面的智能方法是什么?

ruby-on-rails - 如何将常量延迟加载到rails环境中

css - 在我的 Mac 上全局安装 SASS 时出错

ruby - Process.spawn child 没有收到 TERM

javascript - Angular 2 : Simple Get request to external API blocked for CORS but got 200 in network surveillance

python - 身份验证 OneDrive API Python