Требуется авторизация
Вставляет новый контакт. См. пример .
Запрос
HTTP-запрос
POST https://www.googleapis.com/mirror/v1/contacts
Авторизация
Этот запрос требует авторизации со следующей областью действия ( подробнее об аутентификации и авторизации читайте здесь ).
| Объем |
|---|
https://www.googleapis.com/auth/glass.timeline |
Тело запроса
В теле запроса укажите ресурс «Контакты» со следующими свойствами:
| Имя свойства | Ценить | Описание | Примечания |
|---|---|---|---|
| Обязательные свойства | |||
acceptCommands[]. type | string | Тип операции, которому соответствует эта команда. Допустимые значения:
| записываемый |
displayName | string | Имя, которое будет отображаться для этого контакта. | записываемый |
id | string | Идентификатор этого контакта. Он генерируется приложением и рассматривается как непрозрачный токен. | записываемый |
imageUrls[] | list | Набор URL-адресов изображений для отображения для контакта. Большинство контактов будет иметь одно изображение, но «групповой» контакт может включать до 8 URL-адресов изображений, и их размер будет изменен и обрезан в виде мозаики на клиенте. | записываемый |
| Дополнительные свойства | |||
acceptCommands[] | list | Список команд голосового меню, которые может обрабатывать контакт. На стекле отображается до трех контактов для каждой команды голосового меню. Если их больше, для этой конкретной команды отображаются три контакта с наивысшим priority . | записываемый |
acceptTypes[] | list | Список типов MIME, которые поддерживает контакт. Контакт будет показан пользователю, если какой-либо из его AcceptTypes соответствует любому из типов вложений в элементе. Если AcceptTypes не указаны, контакт будет отображаться для всех элементов. | записываемый |
phoneNumber | string | Основной номер телефона для контакта. Это может быть полный номер с кодом страны и кодом города или местный номер. | записываемый |
priority | unsigned integer | Приоритет контакта для определения порядка в списке контактов. Контакты с более высоким приоритетом будут отображаться перед контактами с более низким приоритетом. | записываемый |
speakableName | string | Имя этого контакта как следует произносить. Если имя этого контакта необходимо произнести как часть голосового меню устранения неоднозначности, это имя используется в качестве ожидаемого произношения. Это полезно для имен контактов, содержащих непроизносимые символы или отображаемое написание которых не является фонетическим. | записываемый |
type | string | Тип этого контакта. Это используется для сортировки в пользовательском интерфейсе. Допустимые значения:
| записываемый |
Ответ
В случае успеха этот метод возвращает ресурс «Контакты» в теле ответа.
Примеры
Примечание. Примеры кода, доступные для этого метода, не представляют все поддерживаемые языки программирования (список поддерживаемых языков см. на странице клиентских библиотек ).
Ява
Использует клиентскую библиотеку Java .
import com.google.api.services.mirror.Mirror;
import com.google.api.services.mirror.model.Contact;
import java.io.IOException;
import java.util.Arrays;
public class MyClass {
// ...
/**
* Insert a new contact for the current user.
*
* @param service Authorized Mirror service.
* @param contactId ID of the contact to insert.
* @param displayName Display name for the contact to insert.
* @param iconUrl URL of the contact's icon.
* @return The inserted contact on success, {@code null} otherwise.
*/
public static Contact insertContact(Mirror service, String contactId, String displayName,
String iconUrl) {
Contact contact = new Contact();
contact.setId(contactId);
contact.setDisplayName(displayName);
contact.setImageUrls(Arrays.asList(iconUrl));
try {
return service.contacts().insert(contact).execute();
} catch (IOException e) {
System.err.println("An error occurred: " + e);
return null;
}
}
// ...
}.СЕТЬ
Использует клиентскую библиотеку .NET .
using System;
using System.Collections.Generic;
using Google.Apis.Mirror.v1;
using Google.Apis.Mirror.v1.Data;
public class MyClass {
// ...
/// <summary>
/// Insert a new contact for the current user.
/// </summary>
/// <param name='service'>Authorized Mirror service.</param>
/// <param name='contactId'>ID of the contact to insert.</param>
/// <param name='displayName'>
/// Display name for the contact to insert.
/// </param>
/// <param name='iconUrl'>URL of the contact's icon.</param>
/// <returns>
/// The inserted contact on success, null otherwise.
/// </returns>
public static Contact InsertContact(MirrorService service,
String contactId, String displayName, String iconUrl) {
Contact contact = new Contact() {
Id = contactId,
DisplayName = displayName,
ImageUrls = new List<String>() {iconUrl}
};
try {
return service.Contacts.Insert(contact).Fetch();
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
// ...
}PHP
Использует клиентскую библиотеку PHP .
/**
* Insert a new contact for the current user.
*
* @param Google_MirrorService $service Authorized Mirror service.
* @param string $contactId ID of the contact to insert.
* @param string $displayName Display name for the contact to insert.
* @param string $iconUrl URL of the contact's icon.
* @return Google_Contact The inserted contact on success, null otherwise.
*/
function insertContact($service, $contactId, $displayName, $iconUrl) {
try {
$contact = new Google_Contact();
$contact->setId($contactId);
$contact->setDisplayName($displayName);
$contact->setImageUrls(array($iconUrl));
return $service->contacts->insert($contact);
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
return null;
}
}Питон
Использует клиентскую библиотеку Python .
from apiclient import errors
# ...
def insert_contact(service, contact_id, display_name, icon_url):
"""Insert a new contact for the current user.
Args:
service: Authorized Mirror service.
contact_id: ID of the contact to insert.
display_name: Display name for the contact to insert.
icon_url: URL of the contact's icon.
Returns:
The inserted contact on success, None otherwise.
"""
contact = {
'id': contact_id,
'displayName': display_name,
'imageUrls': [icon_url]
}
try:
service.contacts().insert(body=contact).execute()
except errors.HttpError, error:
print 'An error occurred: %s' % error
return NoneРуби
Использует клиентскую библиотеку Ruby .
##
# Insert a new contact for the current user.
#
# @param [Google::APIClient] client
# Authorized client instance.
# @param [String] contact_id
# ID of the contact to insert.
# @param [String] display_name
# Display name for the contact to insert.
# @param [String] image_url
# URL of the contact's icon.
# @return [Google::APIClient::Schema::Mirror::V1::Contact]
# The inserted contact on success, nil otherwise.
def insert_contact(client, contact_id, display_name, image_url)
mirror = client.discovered_api('mirror', 'v1')
contact = mirror.contacts.insert.request_schema.new({
'id' => contact_id,
'displayName' => display_name,
'imageUrls' => [image_url]
})
result = client.execute(
:api_method => mirror.contacts.insert,
:body_object => contact)
if result.success?
return result.data
else
puts "An error occurred: #{result.data['error']['message']}"
end
endИдти
Использует клиентскую библиотеку Go .
import (
"code.google.com/p/google-api-go-client/mirror/v1"
"fmt"
)
// InsertContact inserts a new contact for the current user.
func InsertContact(g *mirror.Service, contactId string,
displayName string, iconUrl string) (*mirror.Contact, error) {
s := &mirror.Contact{
Id: contactId,
DisplayName: displayName,
ImageUrls: []string{iconUrl},
}
r, err := g.Contacts.Insert(s).Do()
if err != nil {
fmt.Printf("An error occurred: %v\n", err)
return nil, err
}
return r, nil
}Необработанный HTTP
Не использует клиентскую библиотеку.
POST /mirror/v1/contacts HTTP/1.1 Authorization: Bearer auth token Content-Type: application/json Content-Length: length { "id": "harold" "displayName": "Harold Penguin", "imageUrls": ["https://developers.google.com/glass/images/harold.jpg"] }