I have a problem with Google Contacts API v3. I illustrate below the steps i made.
Implementation authentication mechanism:
public 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);
}
Retrieval of my contacts:
Query 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());
}
When i execute ContactFeed feed = service.getFeed(cQuery, ContactFeed.class);, this method returns an empty list. What is missing?
I would add that I have carried out the same procedure using the api JavaScript v3 on the client side, and it works perfectly.
Thank you!
In this case, you are using Oauth with service account. A service account has two functions. 1.- Is the account associated to the application, you can use it to manage information related to the application like Drive Calendar etc.
2.-To impersonate users and act on their behalf. This is only possible on domain accounts and only after the domain admin has granted the service account permissions for domain wide delegation of authority.
In you code, you are doing the authentication as the service account, and not as your own account. Even that you created a service account in your own developer console, the service account does not have access to your information.
So in this case you are trying to retrieve all the contacts that your service account has, which is none (unless you add some).
In order to retrieve all your contacts, you will have to use 'normal' Oauth and not service account. In a similar way that you did when you tried it with javascript but for installed applications.