2013-06-03 27 views
8

我想在Go中編寫一個簡單的命令行Google Drive api。在我看來,到目前爲止,我已經成功地驗證了應用程序,因爲我可以獲取access_token和refresh_token。在問題發生時,我嘗試使用令牌訪問SDK API,我得到了以下錯誤消息超出未經驗證的使用的每日限制

{ 
"error": { 
"errors": [ 
{ 
    "domain": "usageLimits", 
    "reason": "dailyLimitExceededUnreg", 
    "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.", 
    "extendedHelp": "https://code.google.com/apis/console" 
} 
], 
"code": 403, 
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup." 
} 
} 

我注意到另一個奇怪的是,我沒有看到我的谷歌API控制檯的任何配額信息。所以不知道這是否是問題。但由於我可以被認證,所以我想我應該罰款控制檯API設置。

下面是該API查詢

accessUrl := "https://www.googleapis.com/drive/v2/files" + "?access_token=\"" + accessToken + "\"" 
if res , err := http.Get(accessUrl); err == nil { 
     if b, err2 := ioutil.ReadAll(res.Body); err2 == nil { 
      fmt.Println(string(b)) 
     }else{ 
      fmt.Println(err2) 
     } 
}else{ 
    fmt.Println(err) 
} 
+3

好吧,我設法解決了這個問題。看起來我和許多其他人犯了同樣的錯誤。我忘了在API控制檯中啓用「Drive API」。一旦我做到了,那麼它工作得很好。錯誤信息是真的令人誤解。我希望這可以幫助某人解決方案的tnx – tabiul

+0

,它有幫助! :) –

+1

Drive API在哪裏?我如何啓用? – sureshvv

回答

4

這發生在我的代碼,因爲無論:

  1. 我沒有刷新令牌,我試圖刷新。
  2. 我的令牌已過期,在這種情況下,我需要刷新令牌來獲取新的訪問令牌。
  3. 或者最後我有一個刷新令牌,但是我已經通過撤銷訪問而無意中過期了,所以我可以在測試站點上測試活動站點。

因此,首先檢查以確保您的令牌未過期,默認值爲3600秒或一小時,接下來如果您不確定是否可以隨時刷新令牌。

還記得棘手的事情是,一旦一個應用程序已被授權後續請求到服務器將不會返回刷新令牌,我認爲這是一種愚蠢的,但無論如何是這樣。因此,第一個認證可以獲得刷新令牌,而後續請求則不能。

我使用刷新令牌獲取新的訪問令牌代碼如下所示:

public static String refreshtoken(String refreshToken, SystemUser pUser) throws IOException { 
    HttpParams httpParams = new BasicHttpParams(); 
    ClientConnectionManager connectionManager = new GAEConnectionManager(); 
    HttpClient client = new DefaultHttpClient(connectionManager, httpParams); 
    HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token"); 

    List<NameValuePair> pairs = new ArrayList<NameValuePair>(); 
    pairs.add(new BasicNameValuePair("refresh_token", refreshToken)); 
    pairs.add(new BasicNameValuePair("client_id", "YOUR_CLIENT_ID")); 
    pairs.add(new BasicNameValuePair("client_secret", "YOUR_CLIENT_SECRET")); 
    pairs.add(new BasicNameValuePair("grant_type", "refresh_token")); 

    post.setEntity(new UrlEncodedFormEntity(pairs)); 
    org.apache.http.HttpResponse lAuthExchangeResp = client.execute(post); 
    String responseBody = EntityUtils.toString(lAuthExchangeResp.getEntity()); 
    ObjectMapper mapper = new ObjectMapper(); // can reuse, share 
               // globally 
    Map<String, Object> userData = mapper.readValue(responseBody, Map.class); 

    String access_token = (String) userData.get("access_token"); 
    String token_type = (String) userData.get("token_type"); 
    String id_token = (String) userData.get("token_type"); 
    String refresh_token = (String) userData.get("refresh_token"); 

    return access_token; 

} 

我使用谷歌應用程序引擎,因此必須使用GAEConnectionManager,你在這裏得到這些細節:http://peterkenji.blogspot.com/2009/08/using-apache-httpclient-4-with-google.html

希望這會有所幫助!

相關問題