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."
 }
}

我注意到的另一件奇怪的事情是,我在我的 google 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)
 }  
4

1 回答 1

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;

}

我正在使用 Google App Engine,因此必须使用 GAEConnectionManager,您可以在此处获得这些详细信息:http: //peterkenji.blogspot.com/2009/08/using-apache-httpclient-4-with-google.html

希望这可以帮助!

于 2013-07-18T19:26:52.343 回答