2015-10-20 94 views
1

我的Google Contacts API v3出現問題。我在下面說明了我所做的步驟。Google Contacts API v3,JAVA GET ALL CONTACT「contactFeed.getEntries()is empty」!

  1. 通過Google的控制檯創建client_id,file.p12。
  2. 實現身份驗證機制:

    公共ContactsExample(){

    File p12 = new File("exampleContacts.p12"); 
    
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); 
        GoogleCredential credential = new GoogleCredential.Builder() 
          .setTransport(httpTransport) 
          .setJsonFactory(JacksonFactory.getDefaultInstance()) 
          .setServiceAccountId("[email protected]") 
          .setServiceAccountPrivateKeyFromP12File(p12) 
          .setServiceAccountScopes(Collections.singleton("https://www.google.com/m8/feeds/")) 
          .build(); 
    
    
        if (!credential.refreshToken()) { 
         throw new RuntimeException("Failed OAuth to refresh the token"); 
        } 
        service.setOAuth2Credentials(credential); 
    
        printAllContacts(service); 
    

    }

  3. 檢索我的聯繫人:

查詢cQuery =新的查詢(新的Java .net.URL(「https://www.google.com/m8/feeds/contacts/default/full」)); cQuery.setMaxResults(10);

  ContactFeed feed = service.getFeed(cQuery, ContactFeed.class); 

      for (ContactEntry contact : feed.getEntries()) { 
       System.out.println("name: " + contact.getTitle().getPlainText()); 
      } 

當我執行ContactFeed進料= service.getFeed(cQuery,ContactFeed.class);,則此方法返回一個空列表。什麼不見​​了?

我會補充說,我已經在客戶端使用api JavaScript v3執行了相同的過程,並且它完美地工作。

謝謝!

+0

您的代碼中並不清楚,因此,請仔細檢查:您是否在考慮使用隨時可用的庫,如https://github.com/google/gdata-java-client或http:// cloudsponge .com/contact-importers/gmail? –

+0

我使用第一個:github.com/google/gdata-java-client – emilio86

回答

0

在這種情況下,您正在使用Oauth服務帳戶。服務帳戶有兩個功能。 1.-賬戶是否與應用程序相關聯,您可以使用它來管理與應用程序相關的信息,例如雲端硬盤日曆等。

2.-模仿用戶並以其名義行事。這僅在域帳戶上有效,並且僅在域管理員已授予域wide delegation of authority的服務帳戶權限後纔可用。

在您的代碼中,您正在進行身份驗證作爲服務帳戶,而不是您自己的帳戶。即使您在自己的開發者控制檯中創建了服務帳戶,該服務帳戶也無法訪問您的信息。

因此,在這種情況下,您嘗試檢索您的服務帳戶擁有的所有聯繫人,這些聯繫人都是空的(除非您添加一些聯繫人)。

爲了檢索您的所有聯繫人,您將不得不使用'正常'Oauth而不是服務帳戶。以類似的方式,當你嘗試使用javascript,但是爲installed applications

+0

我使用以下方法獲得授權: GoogleAuthorizationCodeRequestUrl authorizationCodeURL = new GoogleAuthorizationCodeRequestUrl(.......)。 感謝您的支持。 – emilio86