Java 如何在过期后自动更新Gmail凭据

Java 如何在过期后自动更新Gmail凭据,java,google-api,gmail-api,google-oauth,Java,Google Api,Gmail Api,Google Oauth,我使用的是Gmail Java API, API工作正常,当我们授予google帐户访问权限时,凭据存储在本地,但在60分钟凭据过期后,它不会自动更新凭据。当使用我的代码进行调试时,它会在 凭证=应用程序授权(“用户”) 如何处理过期的凭据,它只有在调用oauth2身份验证后才能再次工作。是否可以自动刷新此功能 这是我的代码块 /** * Creates an authorized Credential object. * @return an authorized Cred

我使用的是Gmail Java API, API工作正常,当我们授予google帐户访问权限时,凭据存储在本地,但在60分钟凭据过期后,它不会自动更新凭据。当使用我的代码进行调试时,它会在

凭证=应用程序授权(“用户”)

如何处理过期的凭据,它只有在调用oauth2身份验证后才能再次工作。是否可以自动刷新此功能 这是我的代码块

/**
     * Creates an authorized Credential object.
     * @return an authorized Credential object.
     * @throws IOException
     */
    public static Credential authorize() throws IOException {
        // Load client secrets.
        InputStream in =
                Quickstart.class.getResourceAsStream("/client_secret.json");
        GoogleClientSecrets clientSecrets =
                GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        User user =  (User) session.getAttribute("USER");
        java.io.File DATA_STORE_DIR = new java.io.File(
                //System.getProperty("user.home"), ".credentials/"+user.getUserAccountId()+"/gmail-java-quickstart");
                Common.commonPath+File.separator+"client_secrets"+File.separator+user.getUserAccountId()+"/gmail-java-quickstart");
        DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow.Builder(
                        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                        .setDataStoreFactory(DATA_STORE_FACTORY)
                        .setAccessType("offline")
                        .build();
        System.out.println("*************getApprovalPrompt:"+flow.getApprovalPrompt());
        AuthorizationCodeInstalledApp app = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()){
            protected void onAuthorization(AuthorizationCodeRequestUrl authorizationUrl) throws java.io.IOException {
                //System.out.println("authorizationUrl:"+authorizationUrl);
            }
        };
        Credential credential = app.authorize("user");
        //System.out.println("*************AUTH_KKEY:"+credential.getAccessToken());
        //System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
        return credential;
    }

    /**
     * Build and return an authorized Gmail client service.
     * @return an authorized Gmail client service
     * @throws IOException
     */
    public static Gmail getGmailService() throws IOException {
        Credential credential = authorize();
        return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME)
                .build();
    }

    public List<Message> listMessagesWithLabels(List<String> labelIds,StringBuilder paginationtokenBuilder,Long maxResults) throws IOException {
        List<Message> messages = new ArrayList<Message>();
        try {
            Gmail service = getGmailService();
            // some logic bla bla
        }catch(Exception ex){
            ex.printStackTrace();
            return messages;
        }
    }
/**
*创建授权凭据对象。
*@返回授权凭证对象。
*@抛出异常
*/
公共静态凭据授权()引发IOException{
//加载客户端机密。
输入流输入=
Quickstart.class.getResourceAsStream(“/client_secret.json”);
谷歌客户机密=
load(JSON_工厂,新的InputStreamReader(in));
HttpServletRequest请求=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
HttpSession session=request.getSession();
User=(User)session.getAttribute(“用户”);
java.io.File DATA\u STORE\u DIR=new java.io.File(
//System.getProperty(“user.home”),“.credentials/”+user.getUserAccountId()+”/gmail java quickstart”);
Common.commonPath+File.separator+“client_secrets”+File.separator+user.getUserAccountId()+“/gmail java quickstart”);
DATA\u STORE\u FACTORY=新文件datastorefactory(DATA\u STORE\u DIR);
//生成流并触发用户授权请求。
GoogleAuthorizationCodeFlow=
新的GoogleAuthorizationCodeFlow.Builder(
HTTP_传输、JSON_工厂、客户端机密、作用域)
.setDataStoreFactory(数据存储工厂)
.setAccessType(“脱机”)
.build();
System.out.println(“************getApprovalPrompt:“+flow.getApprovalPrompt()”);
AuthorizationCodeInstalledApp app=新的AuthorizationCodeInstalledApp(流程,新的LocalServerReceiver()){
受保护的void onAuthorization(AuthorizationCodeRequestUrl authorizationUrl)引发java.io.IOException{
//System.out.println(“authorizationUrl:+authorizationUrl”);
}
};
凭证=应用程序授权(“用户”);
//System.out.println(“************验证:“+credential.getAccessToken());
//System.out.println(“凭证保存到”+DATA\u STORE\u DIR.getAbsolutePath());
返回凭证;
}
/**
*构建并返回授权的Gmail客户端服务。
*@返回授权的Gmail客户端服务
*@抛出异常
*/
公共静态Gmail GetGmail服务()引发IOException{
凭证=授权();
返回新的Gmail.Builder(HTTP_传输、JSON_工厂、凭证)
.setApplicationName(应用程序名称)
.build();
}
公共列表listMessagesWithLabels(列表标签ID、StringBuilder分页KenBuilder、Long maxResults)引发IOException{
列表消息=新建ArrayList();
试一试{
Gmail服务=GetGmail服务();
//一些逻辑废话
}捕获(例外情况除外){
例如printStackTrace();
返回消息;
}
}

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):

清理过期令牌的服务:

@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();
        }

    }

我知道这可能不是一个合适的解决方案,但这是我尝试的解决方法,因此,请让我们所有人都知道是否有什么方法可以让它变得更好。

有点晚了,但您是否在同一台计算机上为同一用户帐户运行多个电子邮件地址的代码?您的代码似乎应该可以正常工作。我只能认为刷新令牌不起作用,因为您硬编码了
userId
,它是
“user”
。它可能会覆盖具有相同用户ID的不同用户的凭据。
@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();
        }

    }