当前位置 : 主页 > 编程语言 > ruby >

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

来源:互联网 收集:自由互联 发布时间:2021-06-23
我有一个方法适用于非ssl apis的调用,但每当我请求https-only apis时它会给我以下错误响应: 757: unexpected token at '!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"htmlheadtitle400 Bad Request/title/headbodyh1Bad
我有一个方法适用于非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请求?

有一种更优雅的方式来重用您的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.

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

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

网友评论