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

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

概述我有一个方法适用于非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 R 我有一个方法适用于非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 = truehttp.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.

总结

以上是内存溢出为你收集整理的ruby-on-rails – 在Ruby中通过SSL进行API调用全部内容,希望文章能够帮你解决ruby-on-rails – 在Ruby中通过SSL进行API调用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1232708.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存