Hay,我也遇到了同样的问题,但在API方面运气不佳。我有一些解决问题的方法,看看是否有用。
当令牌过期时,API会发出异常(在某些情况下是超时)。这里可以手动刷新令牌(可能带有catch块)。随后的请求将继续使用由前一个请求刷新的更新令牌。下面的代码段。
例外情况下:
try {
response1 = Quickstart.getGmailService().users().messages().list(userId).setLabelIds(labelIds).execute();
return response1.getResultSizeEstimate();
} catch (com.google.api.client.auth.oauth2.TokenResponseException e) {
e.printStackTrace();
FileUtils.deleteDirectory(new File(CLIENT_SECRET_PATH+File.separator+"client_secrets"));
response.sendRedirect("/dashboard"); // redirect to your oauth request URI
} catch (IOException e) {
e.printStackTrace();
}
如果超时(UI):
$.ajax({
url:"listGmailLabels", // Request that is hitting Gmail API
type:"POST",
success:function(data){
// Success logic goes here
},
complete:function(event){
if(event.status == 504){
alert('Token expired! Getting a new refresh token.');
$.ajax({
url:"clearClientSecret", // service call to cleanup the expired token
success:function(){
window.location.reload();
}
})
}
}
});
清理过期令牌的服务:
@RequestMapping(value="/clearClientSecret",method= {RequestMethod.POST,RequestMethod.GET})
public void clearClientSecret(HttpServletRequest request,HttpServletResponse response) {
try {
String path=CLIENT_SECRET_PATH+File.separator+"client_secrets";
FileUtils.deleteDirectory(new File(path));
response.sendRedirect("/dashboard");// redirect to your oauth request URI
} catch (IOException e1) {
e1.printStackTrace();
}
}
我知道这可能不是一个合适的解决方案,但这正是我所尝试的解决方案,所以请让我们所有人都知道是否有什么可以让它变得更好。