加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 01:31:46 所属栏目:百科 来源:网络整理
导读:我有一个方法适用于非ssl apis的调用,但每当我请求https-only apis时它会给我以下错误响应: 757: unexpected token at '!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"htmlheadtitle400 Bad Request/title/headbodyh1Bad Request/h1pYour browser sent
我有一个方法适用于非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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读