【问题标题】:Access Gmail using the Gmail SDK with accessToken?使用带有 accessToken 的 Gmail SDK 访问 Gmail?
【发布时间】:2017-02-27 06:58:22
【问题描述】:

我正在关注guide 构建一个 Android 应用程序,该应用程序请求用户使用 Gmail 范围为只读的帐户访问权限,然后生成 authCode 并将其发送到后端服务器。

后端服务器然后接收 authCode 并使用它生成 accessToken。这是代码:

private static String CLIENT_SECRET_FILE = "/client_secret.json";

private static String REDIRECT_URI = "";

String accessToken = null;

// Exchange auth code for access token
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.class.newInstance(),
                new FileReader(CLIENT_SECRET_FILE));

GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(),
                JacksonFactory.class.newInstance(), "https://www.googleapis.com/oauth2/v4/token",
                clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret(), authCode,
                REDIRECT_URI).execute();

accessToken = tokenResponse.getAccessToken();

现在使用此访问令牌,后端服务器需要使用 Gmail SDK 访问 Gmail

我如何做到这一点?

【问题讨论】:

    标签: java gmail access-token


    【解决方案1】:

    在阅读了几个小时的文档后,我终于弄明白了:

    static final String APPLICATION_NAME = "POC";
    
    /**
    * Global instance of the JSON factory.
    */
    static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    
    /** Global instance of the HTTP transport. */
    static HttpTransport HTTP_TRANSPORT;
    
    public Gmail getGmailService(String accessToken) throws IOException {
        GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
        return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
    }
    

    使用此 Gmail 对象,您可以提出进一步的请求。

    【讨论】:

      猜你喜欢
      • 2013-01-18
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 2017-05-23
      • 2014-10-29
      • 1970-01-01
      • 2014-03-13
      相关资源
      最近更新 更多