使用Ruby执行Google Fusion Tables API命令时,为什么会出现401错误?

时间:2013-03-26 16:53:47

标签: ruby google-api oauth-2.0 google-api-client google-api-ruby-client

我正在使用Ruby gem'google-api-client',我确保添加所有凭据,但出于某种原因,我不断收到来自Google的401错误。

这是我的代码:

['google/api_client','json'].each{|g| require g}

client_secrets = File.open('client_secrets.json','r').read # My client secrets are stored in this .JSON file
client_secrets_hsh = JSON.parse(client_secrets)

client = Google::APIClient.new
client.authorization.client_id = client_secrets_hsh['installed']['client_id']
client.authorization.client_secret = client_secrets_hsh['installed']['client_secret']
client.authorization.redirect_uri = client_secrets_hsh['installed']['redirect_uris'][0]
client.authorization.access_token = 'MY_ACCESS_TOKEN'
client.authorization.username = 'MY_USER_NAME@gmail.com'
client.authorization.password = 'MY_GOOGLE_ACCOUNT_PASSWORD'
client.authorization.scope = 'https://www.googleapis.com/auth/fusiontables'

request_body = ''
headers = []
headers << ['Content-Type','application/json']

api = client.discovered_api('fusiontables','v1')

result = client.execute(
    :api_method => api.to_h['fusiontables.table.list'],
    :parameters => {'maxResults' => 1000},
    :merged_body => request_body,
    :headers => headers
)

puts result.response.body

以下是我从puts results.response.body行回复的回复:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "authError",
    "message": "Invalid Credentials",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Invalid Credentials"
 }
} 

1 个答案:

答案 0 :(得分:1)

不应提供用户名和密码。尝试放弃那些开始。您只需要访问令牌即可进行API调用。顺便说一下,我不确定你从哪里得到它。通常你需要在某处调用fetch_access_token!。它通常不是你通过访问器设置的东西。有些高级案例可以 - 但你可能不是其中之一。