我有一个方法可以很好地调用非 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/