1

我正在使用谷歌自定义搜索 api,我正在尝试通过一些 ruby​​ 代码访问它:

这是代码片段

req = Typhoeus::Request.new("https://www.googleapis.com/customsearch/v1?key={my_key}&cx=017576662512468239146:omuauf_lfve&q=" + keyword, followlocation: true)
res = req.run

答案的主体似乎是这个:

    <p>Your client has issued a malformed or illegal request.  <ins>That’s all we know.</ins>
'
    from /usr/local/lib/ruby/2.1.0/json/common.rb:155:in `parse'
    from main.rb:20:in `initialize'
    from main.rb:41:in `new'
    from main.rb:41:in `<main>'

当我尝试从浏览器做同样的事情时,它就像一个魅力。更令人困惑的是,同样的代码在 12 小时前工作。我只更改了它应该查找的关键字,但是它开始返回错误。

有什么建议么?我确定我有足够的积分来处理更多请求

4

1 回答 1

1

您的 get 参数中的特殊字符可能存在问题keyword。如果您在浏览器中输入 URL,浏览器会对其进行调整。但是,对于 ruby​​,您需要对这些字符进行转义,以使字符串之类的"sky line"变为"sky+line"等等。有一个实用函数CGI::escape,使用如下:

require 'cgi'
CGI::escape("sky line")
=> "sky+line"

您的固定代码如下所示:

req = Typhoeus::Request.new("https://www.googleapis.com/customsearch/v1?key={my_key}&cx=017576662512468239146:omuauf_lfve&q=" + CGI::escape(keyword), followlocation: true)
res = req.run

但是,由于您无论如何都在使用 Typhoeus,您应该能够使用它的params参数并让 Typhoeus 处理转义:

req = Typhoeus::Request.new(
  "https://www.googleapis.com/customsearch/v1?&cx=017576662512468239146:omuauf_lfve",
   followlocation: true, 
   params: {q: keyword, key: my_key}
)
res = req.run

Typhoeus 的 GitHub 页面上有更多示例。

于 2014-03-29T21:34:37.663 回答