Bing搜索API通过Ruby限制

时间:2012-12-12 13:41:02

标签: ruby azure bing-api

我正在尝试获取Bing搜索结果以进行查询。我正在使用Ruby和curb,但无法从API服务器获得任何结果。我总是得到400 Bad Request

这是API文档对PHP的说法 enter image description here

这是我的代码:

require 'curb'
require 'base64'

acctKey = "something"
authKey = Base64.encode64("#{acctKey}:#{acctKey}")
http = Curl.get("https://api.datamarket.azure.com/Bing/Search/Web?$format=json&Query=%27Xbox%27") do |http|
    http.headers['Authorization'] = "Basic #{authKey}"
    http.headers['request_fulluri'] = true
    http.headers['ignore_errors'] = false
    http.verbose = true
end

结果如下:

* About to connect() to api.datamarket.azure.com port 443 (#0)
*   Trying 157.55.194.132...
* Connected to api.datamarket.azure.com (157.55.194.132) port 443 (#0)
* Connected to api.datamarket.azure.com (157.55.194.132) port 443 (#0)
* SSL connection using AES128-SHA
* Server certificate:
*    subject: C=US; ST=WA; L=Redmond; O=Microsoft; OU=STBOS-Clouddb; CN=api.datamarket.azure.com
*    start date: 2012-08-31 18:37:12 GMT
*    expire date: 2013-07-31 21:26:57 GMT
*    common name: api.datamarket.azure.com (matched)
*    issuer: DC=com; DC=microsoft; DC=corp; DC=redmond; CN=Microsoft Secure Server Authority
*    SSL certificate verify ok.
> GET /Bing/Search/Web?$format=json&Query=%27Xbox%27& HTTP/1.1
Host: api.datamarket.azure.com
Accept: */*
request_fulluri: true
ignore_errors: false
Authorization: Basic ...

< HTTP/1.1 400 Bad Request
< Content-Type: text/html; charset=us-ascii
< Server: Microsoft-HTTPAPI/2.0
< Date: Wed, 12 Dec 2012 13:30:22 GMT
< Connection: close
< Content-Length: 339
< 
* Closing connection #0

会出现什么问题?

1 个答案:

答案 0 :(得分:2)

试试这个:

require 'curb'
require 'base64'

acctKey = "<YOUR KEY>"
authKey = Base64.strict_encode64("#{acctKey}:#{acctKey}")
http = Curl.get("https://api.datamarket.azure.com/Bing/Search/Web", {:$format => "json", :Query => "'Xbox'"}) do |http|
    http.headers['Authorization'] = "Basic #{authKey}"
    http.verbose = true
end

puts http.body_str

注意几件事:

  1. Base64.encode64返回带换行符的字符串。 strict_encode64会避免这个问题。 (您也可以删除换行符。)
  2. 我将查询参数直接放在URL中时遇到了麻烦。我只是将参数移到哈希中,这可能是更典型的方法。
  3. EDIT )我还拿出了两个伪造的标题“request_fulluri”和“ignore_errors”。我不认为这些是Perl代码中的实际标头。我没有尝试让他们进去,所以也许他们是无害的,但我认为你不想要他们。