完成「準備使用 People API」一文中的步驟後,您就可以讀取目錄聯絡人和設定檔。
以下程式碼範例示範如何傳送幾個簡單的要求。如需完整的方法清單,請參閱參考說明文件。
列出目錄人員
如要取得使用者網域目錄中的聯絡人和設定檔清單,請使用下列程式碼:
GET /v1/people:listDirectoryPeople?sources=DIRECTORY_SOURCE_TYPE_DOMAIN_CONTACT&sources=DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE&readMask=names,emailAddresses HTTP/1.1
Host: people.googleapis.com
List<String> sources = new ArrayList<>();
sources.add("DIRECTORY_SOURCE_TYPE_DOMAIN_CONTACT");
sources.add("DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE");
ListDirectoryPeopleResponse response = peopleService.people().listDirectoryPeople()
.setSources(sources)
.setReadMask("metadata,names,emailAddresses")
.execute();
List<Person> people = response.getPeople();
列出變更的目錄人員
// Initial request
List<String> sources = new ArrayList<>();
sources.add("DIRECTORY_SOURCE_TYPE_DOMAIN_CONTACT");
sources.add("DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE");
ListDirectoryPeopleResponse fullSyncResponse = peopleService.people().listDirectoryPeople()
.setSources(sources)
.setReadMask("metadata,names,emailAddresses")
.setRequestSyncToken(true)
.execute();
// Fetch all the pages
while (fullSyncResponse.getNextPageToken() != null) {
fullSyncResponse = peopleService.people().listDirectoryPeople()
.setSources(sources)
.setReadMask("metadata,names,emailAddresses")
.setRequestSyncToken(true)
.setPageToken(fullSyncResponse.getNextPageToken())
.execute();
}
// Some time passes
// Fetch incremental changes using the sync token returned in the last fullSyncResponse.
try {
ListDirectoryPeopleResponse incrementalSyncResponse = peopleService.people().listDirectoryPeople()
.setSources(sources)
.setReadMask("metadata,names,emailAddresses")
.setSyncToken(fullSyncResponse.getNextSyncToken())
.execute();
for (Person person : incrementalSyncResponse.getDirectoryPeople()) {
handlePerson(person);
}
// Fetch all the pages
while (incrementalSyncResponse.getNextPageToken() != null) {
incrementalSyncResponse = peopleService.people().listDirectoryPeople
.setSources(sources)
.setReadMask("metadata,names,emailAddresses")
.setSyncToken(fullSyncResponse.getNextSyncToken())
.setPageToken(incrementalSyncResponse.getNextPageToken())
.execute();
for (Person person : incrementalSyncResponse.getDirectoryPeople()) {
handlePerson(person);
}
}
} catch (GoogleJsonResponseException e) {
if (e.getStatusCode() == 410) {
// Sync token expired. Make full sync request.
}
}
void handlePerson(Person person) {
if (person.getMetadata().getDeleted()) {
// Handle deleted person
} else {
// Handle changed person
}
}
如要進一步瞭解同步行為,請參閱 ListDirectory。
搜尋目錄使用者
如要取得使用者網域目錄中符合前置字元查詢的聯絡人和設定檔清單,請使用以下程式碼:
POST /v1/people:searchDirectoryPeople?query=John&sources=DIRECTORY_SOURCE_TYPE_DOMAIN_CONTACT&sources=DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE&readMask=names,emailAddresses HTTP/1.1
Host: people.googleapis.com
List