使用ruby从Google Custom Search API检索JSON信息

时间:2022-08-22 10:19:38

I'm currently using Google's RESTful Custom Search API in order to retrieve Google custom search results in the JSON format. My code looks something like this:

我目前正在使用Google的RESTful Custom Search 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}`

With the key, cx, query and alt variables all having been given suitable values. Now, when I copy and paste the uri string into my browser, I get back the JSON information I was expecting. However, when I try run the code, Firefox opens a page containing only the following message:

使用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."}}

This message also appears if I try running puts r.body instead of writing to file and opening in the browser. Can someone tell me what's going wrong?

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

1 个解决方案

#1


1  

Net::HTTP uses http without SSL (https) by default. You can see the instructions here: http://www.rubyinside.com/nethttp-cheat-sheet-2940.html under "SSL/HTTPS request"

默认情况下,Net :: HTTP使用http而不使用SSL(https)。您可以在此处查看说明:http://www.rubyinside.com/nethttp-cheat-sheet-2940.html“SSL / 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}`

#1


1  

Net::HTTP uses http without SSL (https) by default. You can see the instructions here: http://www.rubyinside.com/nethttp-cheat-sheet-2940.html under "SSL/HTTPS request"

默认情况下,Net :: HTTP使用http而不使用SSL(https)。您可以在此处查看说明:http://www.rubyinside.com/nethttp-cheat-sheet-2940.html“SSL / 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}`