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:
require 'uri'
require 'net/http'
params = "key=#{key}&cx=#{cx}&q=#{query}&alt=#{alt}"
uri = "https://www.googleapis.com/customsea开发者_StackOverflow社区rch/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:
{"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?
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"
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}`
精彩评论