Gmail API access using Android

非 Y 不嫁゛ 提交于 2019-11-30 11:59:56

That error message is deceptive, I believe it also happens when the developer project credentials client isn't correct. For example you picked "web application" when really you want "installed application".

Confirm you're correctly following instructions from: https://developers.google.com/accounts/docs/OAuth2

(Should be "installed application", etc.)

Can you post the oauth client info you have from the developers console? (Type and any other non-confidential info in there, etc.)

Although it's not described clearly, the problem is that the token obtained via GoogleAuthUtil.getToken() is cached locally and may expire. The 403 error you're receiving is due to an expired token. The correct way to handle this situation is to call GoogleAuthUtil.clearToken() to remove the locally cached token, and then call GoogleAuthUtil.getToken() to get a new one.

Alternatively, you can keep track of the last time you requested a token, and if it's been greater than an hour (the default expiry time for these tokens) do the clearToken + getToken calls pre-preemptively.

You need to set up your Android app key in Google Dev Console.

  1. Choose your project, select API & Auth, then click Credentials
  2. Create new client id (though it has other client ids)
  3. Select installed app -> android
  4. Fill in your package name and SHA1 correctly
  5. Create new Key (though it has other client keys)
  6. Select Android key
  7. Fill in the SHA1;packageName like this: 45:B5:E4:6F:36:AD:0A:98:94:B4:02:66:2B:12:17:F2:56:26:A0:E0;com.example

Your problem will be automatically solved. Be sure to create client id and key with both your debug keystore and release keystore.

Well here's the deal. So far Tokens given by GoogleAuthUtil && AccountManager do not work with the Gmail API. Don't know if it's a Google thing or not but my solution is this:

Create a Client Id (Applicaion->Other) in the API console. Use the Client Id & Client secret to obtain an Access Token through a WebView. Save the result Refresh Token. Now whenever you want to refresh the Access Token use this request:

    httpClient = new DefaultHttpClient();
    httpPost = new HttpPost(address);
    params.add(new BasicNameValuePair("refresh_token", token));
    params.add(new BasicNameValuePair("client_id", client_id));
    params.add(new BasicNameValuePair("client_secret", client_secret));
    params.add(new BasicNameValuePair("grant_type", "refresh_token"));
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    httpPost.setEntity(new UrlEncodedFormEntity(params));
    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

Works for me. Hope That in the future a valid token will be provided with the GoogleAuthUtil.getToken() option.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!