简体   繁体   English

使用Android进行Gmail API访问

[英]Gmail API access using Android

I am trying to access the Gmail API using an Android application. 我正在尝试使用Android应用程序访问Gmail API。 I have successfully requested and received an access token using all available scope combinations. 我已成功请求并使用所有可用范围组合接收了访问令牌。 But it seems that every time I actually try to use the Gmail API command I am getting a 403 exception reading: Access not configured please use Google developers console to activate the api... 但似乎每次我实际尝试使用Gmail API命令时,我都会收到403 exception reading: Access not configured please use Google developers console to activate the api...

Needless to say the API is activated and a client key was created using the correct package name & sha1 code. 不用说,API已激活,并且使用正确的包名称和sha1代码创建了客户端密钥。 Same client ID works well with Google Plus features. 相同的客户端ID适用于Google Plus功能。

Anyone having this issue or succeeded in connecting to the Gmail api from Android? 是否有任何人遇到此问题或成功连接到Android的Gmail API?

Thanks 谢谢

Here's the log: 这是日志:

09-04 21:40:54.014: W/System.err(26717): com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
09-04 21:40:54.014: W/System.err(26717): {
09-04 21:40:54.014: W/System.err(26717):   "code" : 403,
09-04 21:40:54.014: W/System.err(26717):   "errors" : [ {
09-04 21:40:54.014: W/System.err(26717):     "domain" : "usageLimits",
09-04 21:40:54.014: W/System.err(26717):     "message" : "Access Not Configured. Please use Google Developers Console to activate the API for your project.",
09-04 21:40:54.014: W/System.err(26717):     "reason" : "accessNotConfigured"
09-04 21:40:54.014: W/System.err(26717):   } ],
09-04 21:40:54.014: W/System.err(26717):   "message" : "Access Not Configured. Please use Google Developers Console to activate the API for your project."
09-04 21:40:54.014: W/System.err(26717): }

Are there any other API's that need to be enabled in the API Console except Google+ API and Gmail API? 是否需要在API控制台中启用除Google+ API和Gmail API之外的任何其他API?

EDIT: 编辑:

I have found out that using a WebView based authentication will result in an access token that will grant Gmail API access but this is not a valid solution because the token is short lived. 我发现使用基于WebView的身份验证将导致访问令牌授予Gmail API访问权限,但这不是有效的解决方案,因为令牌是短暂的。 As for now the GoogleAuthUtil will grant a token but it's privileges are not sufficient for using the Gmail API. 至于现在,GoogleAuthUtil会授予令牌,但它的权限不足以使用Gmail API。 anyone had success in connecting Android with the Gmail API and would like to share? 有人成功将Android与Gmail API连接并希望分享?

EDIT2: EDIT2:

Here are snippets of what I am doing: 以下是我正在做的片段:

Getting the token: 获得令牌:

token = GoogleAuthUtil.getToken(MainActivity.this, Plus.AccountApi.getAccountName(mGoogleApiClient), scope);

Trying to fetch messages from the Gmail API: 尝试从Gmail API获取邮件:

GoogleCredential credential = new GoogleCredential().setAccessToken(token);
JsonFactory jsonFactory = new JacksonFactory();
HttpTransport httpTransport = new NetHttpTransport();

service = new Gmail.Builder(httpTransport, jsonFactory, credential).setApplicationName("GmailApiTP").build();
ListMessagesResponse messagesRespose;
List<Message> m = null;

ArrayList<String> ids = new ArrayList<String>();
ids.add("INBOX");
try {
    messagesRespose = service.users().messages().list("me").setLabelIds(ids).setQ("From: something")
            .execute();
    m = messagesRespose.getMessages();

} catch (IOException e) {
    e.printStackTrace();
}

The exception is caught when use the Gmail API service. 使用Gmail API服务时会遇到异常。 In addition I have tried clearing the token and asking for a new one with the same result. 此外,我已经尝试清除令牌并要求一个具有相同结果的新令牌。

Although it's not described clearly, the problem is that the token obtained via GoogleAuthUtil.getToken() is cached locally and may expire. 虽然没有清楚地描述,但问题是通过GoogleAuthUtil.getToken()获得的令牌在本地缓存并且可能会过期。 The 403 error you're receiving is due to an expired token. 您收到的403错误是由于令牌过期造成的。 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. 处理这种情况的正确方法是调用GoogleAuthUtil.clearToken()来删除本地缓存的令牌,然后调用GoogleAuthUtil.getToken()来获取新的令牌。

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. 或者,您可以跟踪上次请求令牌的时间,如果它超过一小时(这些令牌的默认到期时间),则抢先执行clearToken + getToken调用。

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". 例如,当您真正想要“已安装的应用程序”时,您选择了“Web应用程序”。

Confirm you're correctly following instructions from: https://developers.google.com/accounts/docs/OAuth2 确认您正确遵循以下说明: 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? 你可以从开发者控制台发布你的oauth客户端信息吗? (Type and any other non-confidential info in there, etc.) (在那里输入类型和任何其他非机密信息等)

You need to set up your Android app key in Google Dev Console. 您需要在Google Dev Console中设置Android应用密钥。

  1. Choose your project, select API & Auth, then click Credentials 选择您的项目,选择API&Auth,然后单击凭据
  2. Create new client id (though it has other client ids) 创建新的客户端ID(尽管它有其他客户端ID)
  3. Select installed app -> android 选择已安装的应用程序 - > android
  4. Fill in your package name and SHA1 correctly 正确填写您的包名和SHA1
  5. Create new Key (though it has other client keys) 创建新密钥(尽管它有其他客户端密钥)
  6. Select Android key 选择Android密钥
  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 填写SHA1; packageName如下: 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. 确保使用调试密钥库和发布密钥库创建客户端ID和密钥。

Well here's the deal. 那么这就是交易。 So far Tokens given by GoogleAuthUtil && AccountManager do not work with the Gmail API. 到目前为止,GoogleAuthUtil && AccountManager提供的令牌无法与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. 在API控制台中创建客户端ID(应用程序 - >其他)。 Use the Client Id & Client secret to obtain an Access Token through a WebView. 使用客户端ID和客户端密钥通过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. 希望以后将使用GoogleAuthUtil.getToken()选项提供有效的令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM