Gmail API:Gmail API的凭据

时间:2015-04-14 09:53:54

标签: java gmail gmail-api

这是针对java的Gmail API快速入门的代码。这是我为应用程序创建凭据所需要做的。

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
    httpTransport, jsonFactory, clientSecrets, Arrays.asList(SCOPE))
    .setAccessType("online")
    .setApprovalPrompt("auto").build();

String url = flow.newAuthorizationUrl().setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
    .build();
System.out.println("Please open the following URL in your browser then type"
    + " the authorization code:\n" + url);

// Read code entered by user.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = null;
try {
   code = br.readLine();
} catch (IOException e) {
   e.printStackTrace();
}

// Generate Credential using retrieved code.
GoogleTokenResponse response = null;
try {
   response = flow.newTokenRequest(code)
           .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).execute();
} catch (IOException e) {
   e.printStackTrace();
}
GoogleCredential credential = new GoogleCredential()
    .setFromTokenResponse(response);

我可以采取哪些措施来实现上述流程的自动化,就像在此处获取凭证以供进一步使用一样?以下示例适用于Google Tasks。

GoogleAccountCredential credential =
          GoogleAccountCredential.usingOAuth2(this, Collections.singleton(TasksScopes.TASKS));

2 个答案:

答案 0 :(得分:1)

GoogleCredential credential = new GoogleCredential.Builder()
            .setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY)
            .setServiceAccountId(service_account)
            .setServiceAccountScopes(
                    Collections.singleton("https://mail.google.com/"))
            // .setServiceAccountPrivateKeyFromP12File(new
            // File(certLocation))
            .setServiceAccountPrivateKey(serviceAccountPrivateKey)
            .setServiceAccountUser(senderid).build();

答案 1 :(得分:0)

将此应用程序的用户凭据存储在目录中。

private static final java.io.File DATA_STORE_DIR = new java.io.File(
        System.getProperty("user.home"), ".store/mail_credentials");

FileDataStoreFactory创建一个全局实例。

private static FileDataStoreFactory DATA_STORE_FACTORY;

在最好在静态块中获取凭据之前实例化DATA_STORE_FACTORY

DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);

从Google Developer Console下载并存储client_secrets.json。使用以下方法获取凭据:

public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in
            = GmailQuickStart.class.getResourceAsStream("/client_secrets.json");
    GoogleClientSecrets clientSecrets
            = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // 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();
    Credential credential = new AuthorizationCodeInstalledApp(
            flow, new LocalServerReceiver()).authorize("user");
    System.out.println(
            "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    return credential;
}

每当调用上述方法时,它会在提供给StoredCredential的路径中查找DATA_STORE_DIR。如果找到,则代码按原样执行。如果没有,将打开一个浏览器,要求您登录并授权您的应用。这样生成的凭据将存储在DATA_STORE_DIR位置。只要StoredCredential存在,您的应用就不会要求获得许可。