2015-10-20 96 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