2012-12-12 105 views
1

我試圖讓Bing搜索結果進行查詢。我使用Ruby和curb,但無法從API服務器獲得任何結果。我總是得到400 Bad RequestBing搜索API通過Ruby curb

這是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 

什麼會去錯了嗎?

回答

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. 編輯)我還拿出了兩個假頭「request_fulluri」和「ignore_errors」。我不認爲這些是Perl代碼中的實際標題。我沒有試圖讓他們進入,所以也許他們是無害的,但我不認爲你需要他們。