【问题标题】:Google Contacts API v3, JAVA GET ALL CONTACT "contactFeed.getEntries() is empty"!Google Contacts API v3,JAVA 获取所有联系人“contactFeed.getEntries() 为空”!
【发布时间】:2016-01-19 07:48:33
【问题描述】:

我在使用 Google Contacts API v3 时遇到问题。我在下面说明了我所做的步骤。

  1. 通过 Google 控制台创建 client_id、file.p12。
  2. 实现认证机制:

    public ContactsExample(){

      File p12 = new File("exampleContacts.p12");
    
      HttpTransport httpTransport =  GoogleNetHttpTransport.newTrustedTransport();
      GoogleCredential credential = new GoogleCredential.Builder()
              .setTransport(httpTransport)
              .setJsonFactory(JacksonFactory.getDefaultInstance())
              .setServiceAccountId("xxxxx@developer.gserviceaccount.com")
              .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 = new Query(new 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 feed = service.getFeed(cQuery, ContactFeed.class); 时,此方法返回一个空列表。缺少什么?

我要补充一点,我已经在客户端使用 api JavaScript v3 执行了相同的过程,并且效果很好。

谢谢!

【问题讨论】:

标签: java google-api google-contacts-api google-api-java-client


【解决方案1】:

在这种情况下,您将 Oauth 与服务帐户一起使用。服务帐户有两个功能。 1.- 是与应用关联的帐号,您可以使用它来管理与应用相关的信息,例如云端硬盘日历等。

2.-冒充用户并代表他们行事。这仅适用于域帐户,并且只有在域管理员已授予域 wide delegation of authority 的服务帐户权限之后。

在您的代码中,您是作为服务帐户进行身份验证,而不是作为您自己的帐户。即使您在自己的开发者控制台中创建了服务帐号,该服务帐号也无权访问您的信息。

因此,在这种情况下,您尝试检索您的服务帐户拥有的所有联系人,但没有(除非您添加一些)。

为了检索您的所有联系人,您必须使用“普通”Oauth 而不是服务帐户。与您在使用 javascript 时所做的类似,但使用的是 installed applications

【讨论】:

  • 我使用以下方法获取授权:GoogleAuthorizationCodeRequestUrl authorizationCodeURL = new GoogleAuthorizationCodeRequestUrl (.......)。感谢您的支持。
猜你喜欢
  • 2014-08-15
  • 2019-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-31
  • 2013-09-25
相关资源
最近更新 更多