2012-01-09 59 views
5

我想做相當於例如this API explorer call使用google ruby API client在公共模式下訪問Google+(Ruby)API

那應該很簡單:

require 'rubygems' 
require 'google/api_client' 
require 'httpadapter/adapters/net_http' 

@client = Google::APIClient.new(
    :key => MY_SIMPLE_API_SERVER_KEY, 
    :host => 'www.googleapis.com', 
    :http_adapter => HTTPAdapter::NetHTTPAdapter.new, 
    :pretty_print => false 
) 
@plus = @client.discovered_api('plus', 'v1') 

status, headers, body = @client.execute(
    @plus.people.list_by_activity, 
    'activityId' => 'z12nspyxxufislit423eex442zqpdtqnk', 
    'collection' => 'plusoners', 
    'maxResults' => '100', 
    'authenticated' => 'false' 
) 
public_activity = JSON.parse(body[0]) 

然而,在ArgumentError: Missing access token.

execute通話效果我要登錄用戶;我只想訪問公開的數據。我該怎麼做呢?

回答

3

我在客戶端代碼中搜索並找到了幾個選項。

首先,您可以創建一個API客戶端,使所有請求都不帶訪問令牌。構造函數可能比指定默認值更積極一點。要解決此問題,您可以在創建客戶端後清除身份驗證方法。您的代碼如下所示:

require 'rubygems' 
require 'google/api_client' 
require 'httpadapter/adapters/net_http' 

@client = Google::APIClient.new(
    :key => 'SOME_KEY', 
    :host => 'www.googleapis.com', 
    :http_adapter => HTTPAdapter::NetHTTPAdapter.new, 
    :pretty_print => false 
) 
@client.authorization = nil 

@plus = @client.discovered_api('plus', 'v1') 

status, headers, body = @client.execute(
    @plus.people.list_by_activity, 
    'activityId' => 'z12nspyxxufislit423eex442zqpdtqnk', 
    'collection' => 'plusoners', 
    'maxResults' => '100' 
) 
public_activity = JSON.parse(body[0]) 

或者,您可以基於每個請求重寫身份驗證方法。你很接近這個!你有正確的選項,你只需要在把它作爲像這樣的最終參數:

require 'rubygems' 
require 'google/api_client' 
require 'httpadapter/adapters/net_http' 

@client = Google::APIClient.new(
    :key => 'SOME_KEY', 
    :host => 'www.googleapis.com', 
    :http_adapter => HTTPAdapter::NetHTTPAdapter.new, 
    :pretty_print => false 
) 
@plus = @client.discovered_api('plus', 'v1') 

status, headers, body = @client.execute(
    @plus.people.list_by_activity, 
    {'activityId' => 'z12nspyxxufislit423eex442zqpdtqnk', 
    'collection' => 'plusoners', 
    'maxResults' => '100'}, '', [], {:authenticated => false} 
) 
puts status 
puts body 
public_activity = JSON.parse(body[0]) 

感謝Allen提出這個一個我注意在Google+上:)

+1

'@client.authorization = nil'完全適合我的需求。我會注意到雖然'execute'返回一個'Google :: APIClient :: Result'值,而不是3值數組,所以'status,headers,body ='位是錯誤的('response.status','' response.headers'和'response.body'雖然可以工作)。我會爲此提出一個錯誤。 – Sai 2012-01-10 02:28:32

+1

@Sai:Jenny的回答來自舊版本的客戶端。正如你所說,當前版本返回一個「Result」對象。 – 2012-01-10 06:40:03