Java - GMail API - 授权代码

时间:2016-04-25 06:18:32

标签: java google-oauth gmail-api google-api-java-client

我正在尝试下面的代码。控制台打印出一个URL(在我浏览器的地址栏中粘贴后)将我发送到谷歌的用户同意页面,并要求获得访问我帐户的权限。然后它将我重定向到我的html页面 - 到目前为止一直很好。

现在,我不确定是否收到令牌或授权码。我从哪里获得它?然后我必须从Web应用程序发送HTTP休息呼叫以配合Gmail API请求,还是可以通过JAVA进行?

public class People {
  public void setUp() throws IOException {
        HttpTransport httpTransport = new NetHttpTransport();
        JacksonFactory jsonFactory = new JacksonFactory();

        String clientId = "client_id";
        String clientSecret = "secret";

        String redirectUrl = "http://localhost:8080/TestingGmailMail/webapps/login.html";
        String scope = "https://www.googleapis.com/auth/contacts.readonly";


        String authorizationUrl = new GoogleBrowserClientRequestUrl(clientId,redirectUrl,Arrays.asList(scope)).build();


        // Point or redirect your user to the authorizationUrl.
        System.out.println("Go to the following link in your browser:");
        System.out.println(authorizationUrl);
        }
}

1 个答案:

答案 0 :(得分:0)

是的,@ DalmTo指出客户端库是应该处理所有这些的客户端库是正确的。

更好的设计是将应用程序的用户凭据存储在目录中。

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_secret.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存在,您的应用就不会要求获得许可。这是一种通用设计,也可用于其他Google API。