Требуется авторизация
Обновляет контакт на месте. См. пример .
Запрос
HTTP-запрос
PUT https://www.googleapis.com/mirror/v1/contacts/id
Параметры
Имя параметра | Ценить | Описание |
---|---|---|
Параметры пути | ||
id | string | Идентификатор контакта. |
Авторизация
Этот запрос требует авторизации со следующей областью действия ( подробнее об аутентификации и авторизации ).
Объем |
---|
https://www.googleapis.com/auth/glass.timeline |
Тело запроса
В тексте запроса укажите ресурс «Контакты» со следующими свойствами:
Имя свойства | Ценить | Описание | Примечания |
---|---|---|---|
Требуемые свойства | |||
acceptCommands[]. type | string | Тип операции, которой соответствует эта команда. Допустимые значения:
| доступный для записи |
displayName | string | Имя, отображаемое для этого контакта. | доступный для записи |
id | string | Идентификатор для этого контакта. Он генерируется приложением и рассматривается как непрозрачный токен. | доступный для записи |
imageUrls[] | list | Набор URL-адресов изображений для отображения для контакта. У большинства контактов будет одно изображение, но «групповой» контакт может включать до 8 URL-адресов изображений, и они будут изменены в размере и обрезаны в виде мозаики на клиенте. | доступный для записи |
Дополнительные свойства | |||
acceptCommands[] | list | Список команд голосового меню, которые может обрабатывать контакт. Glass показывает до трех контактов для каждой команды голосового меню. Если их больше, для этой конкретной команды отображаются три контакта с наивысшим priority . | доступный для записи |
acceptTypes[] | list | Список типов MIME, которые поддерживает контакт. Контакт будет показан пользователю, если какой-либо из его acceptTypes соответствует любому из типов вложений в элементе. Если acceptTypes не задан, контакт будет показан для всех элементов. | доступный для записи |
phoneNumber | string | Основной номер телефона контакта. Это может быть полностью определенный номер с телефонным кодом страны и кодом города или местный номер. | доступный для записи |
priority | unsigned integer | Приоритет контакта для определения порядка в списке контактов. Контакты с более высоким приоритетом будут отображаться перед контактами с более низким приоритетом. | доступный для записи |
speakableName | string | Имя этого контакта, как это должно быть произнесено. Если имя этого контакта должно быть произнесено как часть голосового меню устранения неоднозначности, это имя используется в качестве ожидаемого произношения. Это полезно для имен контактов с непроизносимыми символами или чье отображаемое написание не является фонетическим. | доступный для записи |
type | string | Тип этого контакта. Это используется для сортировки в пользовательском интерфейсе. Допустимые значения:
| доступный для записи |
Ответ
В случае успеха этот метод возвращает ресурс Contacts в тексте ответа.
Примеры
Примечание. Примеры кода, доступные для этого метода, не представляют все поддерживаемые языки программирования (список поддерживаемых языков см. на странице клиентских библиотек ).
Джава
Использует клиентскую библиотеку Java .
import com.google.api.services.mirror.Mirror;
import com.google.api.services.mirror.model.Contact;
import java.io.IOException;
public class MyClass {
// ...
/**
* Rename an existing contact for the current user.
*
* @param service Authorized Mirror service.
* @param contactId ID of the contact to rename.
* @param newDisplayName New displayName for the contact.
* @return Patched contact on success, {@code null} otherwise.
*/
public static Contact renameContact(Mirror service, String contactId, String newDisplayName) {
try {
// Get the latest version of the contact from the API.
Contact contact = service.contacts().get(contactId).execute();
contact.setDisplayName(newDisplayName);
// Send an update request to the API.
return service. contacts().update(contactId, contact).execute();
} catch (IOException e) {
System.err.println("An error occurred: " + e);
return null;
}
}
// ...
}
.СЕТЬ
Использует клиентскую библиотеку .NET .
using System; using Google.Apis.Mirror.v1; using Google.Apis.Mirror.v1.Data; public class MyClass { // ... /// <summary> /// Rename an existing contact for the current user. /// </summary> /// <param name='service'>Authorized Mirror service.</param> /// <param name='contactId'>ID of the contact to rename.</param> /// <param name='newDisplayName'> /// New displayName for the contact. /// </param> /// <returns> /// Updated contact on success, null otherwise. /// </returns> public static Contact RRenameContact(MirrorService service, String contactId, String newDisplayName) { try { Contact contact = service.Contacts.Get(contactId).Fetch(); contact.DisplayName = newDisplayName; return service.Contacts.Update(contact, contactId).Fetch(); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return null; } } // ... }
PHP
Использует клиентскую библиотеку PHP .
/** * Rename an existing contact for the current user. * * @param Google_MirrorService $service Authorized Mirror service. * @param string $contactId ID of the contact to rename. * @param string $newDisplayName New displayName for the contact. * @return Google_Contact Updated contact on success, null otherwise. */ function renameContact($service, $contactId, $newDisplayName) { try { $updatedContact = $service->contacts->get($contactId); $updatedContact->setDisplayName($newDisplayName); return $service->contacts->update($contactId, $updatedContact); } catch (Exception $e) { print 'An error occurred: ' . $e->getMessage(); return null; } }
питон
Использует клиентскую библиотеку Python .
from apiclient import errors # ... def rename_contact(service, contact_id, new_display_name): """Rename an existing contact for the current user. Args: service: Authorized Mirror service. contact_id: ID of the contact to rename. new_display_name: New displayName for the contact. Returns: return Patched contact on success, None otherwise. """ try: # Get the latest version of the contact from the API. contact = service.contacts().get(contact_id).execute() contact['displayName'] = new_display_name return service. contacts().update( id=contact_id, body=contact).execute() except errors.HttpError, e: print 'An error occurred: %s' % error return None
Рубин
Использует клиентскую библиотеку Ruby .
## # Rename an existing contact for the current user. # # @param [Google::APIClient] client # Authorized client instance. # @param [String] contact_id # ID of the contact to rename. # @param [String] new_display_name # New displayName for the contact. # @return [Google::APIClient::Schema::Mirror::V1::Contact] # Updated contact on success, nil otherwise. def rename_contact(client, contact_id, new_display_name) mirror = client.discovered_api('mirror', 'v1') # Get the latest version of the contact from the API. result = client.execute( :api_method => mirror.contacts.get, :parameters => { 'id' => contact_id }) if result.success? contact = result.data contact.display_name = new_display_name result = client.execute( :api_method => mirror.contacts.update, :parameters => { 'id' => contact_id }, :body_object => contact) if result.success? return result.data end end puts "An error occurred: #{result.data['error']['message']}" end
Идти
Использует клиентскую библиотеку Go .
import (
"code.google.com/p/google-api-go-client/mirror/v1"
"fmt"
)
// RenameContact renames an existing contact for the current user.
func RenameContact(g *mirror.Service, contactId string,
newDisplayName string) (*mirror.Contact, error) {
s, err := g. Contacts.Get(contactId).Do()
if err != nil {
fmt.Printf("An error occurred: %v\n", err)
return nil, err
}
s.DisplayName = newDisplayName
r, err := g.Contacts.Patch(contactId, s).Do()
if err != nil {
fmt.Printf("An error occurred: %v\n", err)
return nil, err
}
return r, nil
}
Необработанный HTTP
Не использует клиентскую библиотеку.
PUT /mirror/v1/contacts/harold HTTP/1.1 Authorization: Bearer auth token Content-Type: application/json Content-Length: length { "displayName": "Harold Penguin", "imageUrls": ["https://developers.google.com/glass/images/harold.jpg"] }