2016-04-25 81 views
1

我正在嘗試以下代碼。控制檯打印出一個URL(粘貼到我的瀏覽器的地址欄後)將我發送到谷歌的用戶同意頁面,並要求獲得訪問我的帳戶的權限。然後它將我重定向到我的html頁面 - 非常好。Java - GMail API - 授權碼

現在,我不確定我是否收到令牌或授權碼。我從哪裏獲得?然後是否必須發送來自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); 
     } 
} 
+0

我不是一位java專家,但客戶端庫應該爲您處理所有這些問題你有沒有試過閱讀本教程? https://developers.google.com/gmail/api/quickstart/java#prerequisites – DaImTo

+0

非常感謝 - DalmTo!是的,我已經嘗試閱讀它,並發現它非常愚蠢..我會嘗試通過圖書館tho –

+0

當您開始使用Google API時,它非常混亂。我不能幫助java,但也許我可以幫助你一點。 GoogleAuthorizationCodeFlow處理來自用戶的請求認證,它保存認證(不知道在java中的哪個地方)應該是refreshtoken和訪問令牌。 getGmailService將爲您提供訪問API的權限,它將在需要時獲取新的訪問令牌。你所做的一切都將通過Gmail服務 – DaImTo

回答

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; 
} 

當上述方法被調用時,它會在提供給DATA_STORE_DIR的路徑StoredCredential。如果找到,則代碼將按原樣執行。如果沒有,瀏覽器將打開,它會要求您登錄並授權您的應用程序。生成的憑證將存儲在DATA_STORE_DIR位置。只要StoredCredential存在,您的應用程序就不會要求許可。這是一種通用設計,可用於其他Google API。