我得到令牌响应异常后,1-2分钟连续.经过2-3分钟的接触,然后再过2-3分钟,令牌异常就出现了。以下是例外情况
com.google.api.client.auth.oauth2.TokenResponseException: 403 OK
<p class="large"><b>403.</b>
<ins>That's an error.</ins></p><p class="large">You are not authorised to perform this request. <ins>That's all we know.</ins>
</p>我正在检索用户的联系人,下面是我的代码
ContactsService contactService = new ContactsService("appName");
contactService.setOAuth2Credentials(getCredentials());下面是getCredentials()方法。
public GoogleCredential getCredentials() {
GoogleCredential credential = null;
try{
Collection<String> SCOPES = new ArrayList<String>();
SCOPES.add("https://www.googleapis.com/auth/userinfo.profile");
SCOPES.add("https://www.google.com/m8/feeds");
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(SCOPES)
.setServiceAccountUser(adminEmailAddress)
.setServiceAccountPrivateKeyFromP12File(new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
.build().setExpiresInSeconds(min);
credential.refreshToken();
} catch(Exception e){
e.printStackTrace();
}
return credential;
}有人能告诉我如何使令牌在最大时间内有效或如何处理上述问题吗?
发布于 2014-02-11 08:56:29
你需要了解Oauth2的工作原理,我认为你应该读使用Google2.0访问Google
访问令牌的寿命有限。如果您的应用程序在单个访问令牌的生存期之后需要访问Google,它可以获得一个刷新令牌。刷新令牌允许应用程序获得新的访问令牌。
注意:将刷新令牌保存在安全的长期存储中,并继续使用它们,只要它们仍然有效。限制适用于每个客户端-用户组合以及所有客户端的每个用户发出的刷新令牌的数量,而这些限制是不同的。如果应用程序请求足够多的刷新令牌以超出其中一个限制,则旧的刷新令牌将停止工作。
如加法中所述,访问令牌的工作时间有限。一小时就不能再延长了。但是,为了获得一个新的refreshToken,您需要的是AccessToken。除非用户撤销您的访问权限,否则RefreshTokens不会过期。但在你的情况下,这种情况不会发生,因为你使用的是一个服务帐户。这样您就可以重新运行代码并获得一个新的AccessToken。
你有两个选择:
第一种选择是最好的,因为google记录从API获得的错误数量,没有理由运行一些会对您产生错误的东西。通常,在旧的AccessToken到期前5分钟,我会请求一个新的。
https://stackoverflow.com/questions/21676896
复制相似问题