使用带有 accessToken 的 Gmail SDK 访问 Gmail?
Access Gmail using the Gmail SDK with accessToken?
我正在按照此 guide 构建一个 Android 应用程序,该应用程序请求用户以只读方式访问 Gmail 范围的帐户,然后生成一个 authCode 并将其发送到后端服务器。
后端服务器然后接收 authCode 并使用它生成 acessToken。这是它的代码:
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。
如何实现?
看了几个小时的文档后,我终于明白了:
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 对象,您可以提出进一步的请求。
我正在按照此 guide 构建一个 Android 应用程序,该应用程序请求用户以只读方式访问 Gmail 范围的帐户,然后生成一个 authCode 并将其发送到后端服务器。
后端服务器然后接收 authCode 并使用它生成 acessToken。这是它的代码:
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。
如何实现?
看了几个小时的文档后,我终于明白了:
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 对象,您可以提出进一步的请求。