ruby-on-rails – 在Ruby中通过SSL进行API调用
我有一个方法适用于非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开始:
另请注意,自it doesn’t force the validity of of certificates to be checked以来,VERIFY_NONE的使用存在争议.对于许多应用程序和用户而言,这不会产生任何负面影响.如果要检查证书有效性,this post建议如下:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |