使用ruby从Google自定义搜索API检索JSON信息

使用ruby从Google自定义搜索API检索JSON信息,ruby,json,rest,Ruby,Json,Rest,我目前正在使用Google的RESTful定制搜索API,以便以JSON格式检索Google定制搜索结果。我的代码如下所示: require 'uri' require 'net/http' params = "key=#{key}&cx=#{cx}&q=#{query}&alt=#{alt}" uri = "https://www.googleapis.com/customsearch/v1?#{params}" r = Net::HTTP.get_response(

我目前正在使用Google的RESTful定制搜索API,以便以JSON格式检索Google定制搜索结果。我的代码如下所示:

require 'uri'
require 'net/http'

params = "key=#{key}&cx=#{cx}&q=#{query}&alt=#{alt}"
uri = "https://www.googleapis.com/customsearch/v1?#{params}"
r = Net::HTTP.get_response(URI.parse(uri).host, URI.parse(uri).path)

temp_file = 'testfile.html'
File.open(temp_file, 'w') { |f| f.write(r.body) }
`firefox #{temp_file}`
对于key、cx、query和alt变量,它们都被赋予了合适的值。现在,当我将uri字符串复制并粘贴到浏览器中时,我得到了我所期望的JSON信息。但是,当我尝试运行代码时,Firefox会打开一个只包含以下消息的页面:

{"error":{"errors":[{"domain":"global","reason":"sslRequired","message":"SSL is required    to perform this operation."}],"code":403,"message":"SSL is required to perform this operation."}}

如果我尝试运行
put r.body
,而不是写入文件并在浏览器中打开,也会出现此消息。有人能告诉我出了什么问题吗?

Net::HTTP默认使用不带SSL的HTTP(https)。您可以在此处查看说明: 在“SSL/HTTPS请求”下


当我尝试运行该代码时,我收到以下错误消息:未定义的方法'use_ssl='for#(NoMethodError)我的错误,我使用了'net/http'而不是'net/https'是的,对不起,这部分很微妙。
require 'uri'
require 'net/https'

params = "key=#{key}&cx=#{cx}&q=#{query}&alt=#{alt}"
uri = URI.parse("https://www.googleapis.com/customsearch/v1?#{params}")

http= Net::HTTP.new(uri.host,uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
r=http.request(Net::HTTP::Get.new(uri.request_uri))

temp_file = 'testfile.html'
File.open(temp_file, 'w') { |f| f.write(r.body) }
`firefox #{temp_file}`