2016-06-09 14 views
1

Ich möchte mit Google APIs mit einem .NET-Client arbeiten. Für den ersten Schritt habe ich versucht, alle Google-Kontakte zu bekommen und jetzt möchte ich Kontakte einfügen. Ich habe viel über Google APIs zu CRUD (erstellen, lesen, aktualisieren und löschen) Kontakte gelesen. Es gibt die Kontakt-API, die Personen-API und andere (?). Was ist der beste Weg zu CRUD Kontakten?Google-API verwenden, um Google-Kontakte zu ändern

UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
    new ClientSecrets 
    { 
    ClientId = "xyz.apps.googleusercontent.com", 
    ClientSecret = " xyz" 
    }, 
    new[] { "profile", "https://www.google.com/m8/feeds/contacts/xy%40gmail.com/full" }, 
    "me", 
    CancellationToken.None).Result; 

// Create the service. 
var peopleService = new PeopleService(new BaseClientService.Initializer() 
{ 
    HttpClientInitializer = credential, 
    ApplicationName = "WindowsClient-Google-Sync", 
}); 

ListRequest listRequest = peopleService.People.Connections.List("people/me"); 
listRequest.SyncToken = null; 
ListConnectionsResponse result = listRequest.Execute(); 

foreach (Person person in result.Connections) 
{ 
    foreach (Name name in person.Names) 
    { 
    Console.WriteLine("Name: " + name.DisplayName); 
    } 
} 

Wie kann ich dieses Beispiel erweitern, um Kontakte zu erstellen oder zu aktualisieren?

Dank

Andreas

Antwort

1

Wenn Sie überprüfen Google Contacts API:

The Google Contacts API allows client applications to view and update a user's contacts. Contacts are stored in the user's Google Account; most Google services have access to the contact list.

Your client application can use the Google Contacts API to create new contacts, edit or delete existing contacts, and query for contacts that match particular criteria

Kontakt Erstellen

To create a new contact, send an authorized POST request to the user's contacts feed URL with contact data in the body.

Die URL der Form ist:

https://www.google.com/m8/feeds/contacts/{userEmail}/full 

Upon success, the server responds with an HTTP 201 Created status code and the created contact entry with some additional elements and properties (shown in bold) that are set by the server, such as id, various link elements and properties.

import com.google.gdata.client.contacts.ContactsService; 
import com.google.gdata.data.contacts.ContactEntry; 
import com.google.gdata.data.contacts.ContactGroupFeed; 
import com.google.gdata.data.extensions.City; 
import com.google.gdata.data.extensions.Country; 
import com.google.gdata.data.extensions.Email; 
import com.google.gdata.data.extensions.ExtendedProperty; 
import com.google.gdata.data.extensions.FormattedAddress; 
import com.google.gdata.data.extensions.FullName; 
import com.google.gdata.data.extensions.Im; 
import com.google.gdata.data.extensions.Name; 
import com.google.gdata.data.extensions.PhoneNumber; 
import com.google.gdata.data.extensions.PostCode; 
import com.google.gdata.data.extensions.Region; 
import com.google.gdata.data.extensions.Street; 
import com.google.gdata.data.extensions.StructuredPostalAddress; 
// ... 
public static ContactEntry createContact(ContactsService myService) { 
    // Create the entry to insert. 
    ContactEntry contact = new ContactEntry(); 
    // Set the contact's name. 
    Name name = new Name(); 
    final String NO_YOMI = null; 
    name.setFullName(new FullName("Elizabeth Bennet", NO_YOMI)); 
    name.setGivenName(new GivenName("Elizabeth", NO_YOMI)); 
    name.setFamilyName(new FamilyName("Bennet", NO_YOMI)) 
    contact.setName(name); 
    contact.setContent(new PlainTextConstruct("Notes")); 
    // Set contact's e-mail addresses. 
    Email primaryMail = new Email(); 
    primaryMail.setAddress("[email protected]"); 
    primaryMail.setDisplayName("E. Bennet"); 
    primaryMail.setRel("http://schemas.google.com/g/2005#home"); 
    primaryMail.setPrimary(true); 
    contact.addEmailAddress(primaryMail); 
    Email secondaryMail = new Email(); 
    secondaryMail.setAddress("[email protected]"); 
    secondaryMail.setRel("http://schemas.google.com/g/2005#work"); 
    secondaryMail.setPrimary(false); 
    contact.addEmailAddress(secondaryMail); 
    // Set contact's phone numbers. 
    PhoneNumber primaryPhoneNumber = new PhoneNumber(); 
    primaryPhoneNumber.setPhoneNumber("(206)555-1212"); 
    primaryPhoneNumber.setRel("http://schemas.google.com/g/2005#work"); 
    primaryPhoneNumber.setPrimary(true); 
    contact.addPhoneNumber(primaryPhoneNumber); 
    PhoneNumber secondaryPhoneNumber = new PhoneNumber(); 
    secondaryPhoneNumber.setPhoneNumber("(206)555-1213"); 
    secondaryPhoneNumber.setRel("http://schemas.google.com/g/2005#home"); 
    contact.addPhoneNumber(secondaryPhoneNumber); 
    // Set contact's IM information. 
    Im imAddress = new Im(); 
    imAddress.setAddress("[email protected]"); 
    imAddress.setRel("http://schemas.google.com/g/2005#home"); 
    imAddress.setProtocol("http://schemas.google.com/g/2005#GOOGLE_TALK"); 
    imAddress.setPrimary(true); 
    contact.addImAddress(imAddress); 
    // Set contact's postal address. 
    StructuredPostalAddress postalAddress = new StructuredPostalAddress(); 
    postalAddress.setStreet(new Street("1600 Amphitheatre Pkwy")); 
    postalAddress.setCity(new City("Mountain View")); 
    postalAddress.setRegion(new Region("CA")); 
    postalAddress.setPostcode(new PostCode("94043")); 
    postalAddress.setCountry(new Country("US", "United States")); 
    postalAddress.setFormattedAddress(new FormattedAddress("1600 Amphitheatre Pkwy Mountain View")); 
    postalAddress.setRel("http://schemas.google.com/g/2005#work"); 
    postalAddress.setPrimary(true); 
    contactOne.addStructuredPostalAddress(postalAddress); 
    // Ask the service to insert the new entry 
    URL postUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full"); 
    ContactEntry createdContact = myService.insert(postUrl, contact); 
    System.out.println("Contact's ID: " + createdContact.getId()); 
    return createdContact; 
} 

Update Contact

To update a contact, first retrieve the contact entry, modify the data and send an authorized PUT request to the contact's edit URL with the modified contact entry in the body.

Die URL ist von der Form:

https://www.google.com/m8/feeds/contacts/userEmail/full/{contactId} 

Um sicherzustellen, dass die Daten an die API überschreibt nicht anderen Kunden Änderungen gesendet, Das Etag des Kontakteintrags sollte im Anforderungsheader angegeben werden.

If-Match: Etag 

Bei Erfolg antwortet der Server mit einem HTTP 200 OK Statuscode und die aktualisierte Kontakteintrag.

public static ContactEntry updateContactName(
    ContactsService myService, URL contactURL) 
    throws ServiceException, IOException { 
    // First retrieve the contact to updated. 
    ContactEntry entryToUpdate = myService.getEntry(contactURL, ContactEntry.class); 
    entryToUpdate.getName().getFullName().setValue("New Name"); 
    entryToUpdate.getName().getGivenName().setValue("New"); 
    entryToUpdate.getName().getFamilyName().setValue("Name"); 
    URL editUrl = new URL(entryToUpdate.getEditLink().getHref()); 
    try { 
    ContactEntry contactEntry = myService.update(editUrl, entryToUpdate); 
    System.out.println("Updated: " + contactEntry.getUpdated().toString()); 
    return contactEntry; 
    } catch (PreconditionFailedException e) { 
    // Etags mismatch: handle the exception. 
    } 
    return null; 
} 

Kontakt löscht

einen Kontakt zu löschen, eine autorisierte DELETE Anforderung an den Bearbeitungs-URL des Kontakts senden.

Die URL der Form ist:

https://www.google.com/m8/feeds/contacts/{userEmail}/full/{contactId} 

Um sicherzustellen, dass die Daten an das API gesendet nicht überschrieben anderen Änderungen des Kunden, der Etag Kontakteintrag sollte im Request-Header zur Verfügung gestellt werden.

If-Match: Etag 

Bei Erfolg antwortet der Server mit einem HTTP 200 OK Statuscode.

public static void deleteContact(ContactsService myService, URL contactURL) 
    throws ServiceException, IOException { 
    // Retrieving the contact is required in order to get the Etag. 
    ContactEntry contact = myService.getEntry(contactURL, ContactEntry.class); 

    try { 
    contact.delete(); 
    } catch (PreconditionFailedException e) { 
    // Etags mismatch: handle the exception. 
    } 
} 

während People API:

The People API lets you list authenticated users' Contacts and retrieve profile information for authenticated users and their contacts.

For example, let's say the authenticated user, Jen, has Fabian and Ranjith in her private contacts. When your app calls people.connections.list to retrieve a list of her connections, Jen is presented with a consent screen asking to give the app access to the list. If Jen consents, the app retrieves a list containing Fabian and Ranjith (with a resource name for each person). The app can then call people.get, passing in a resource name, to get private contact and public profile data for each person.

+0

Vielen Dank für Ihre Antwort. Der Browser öffnet die Google-Website, um Zugriffsrechte zu erteilen. Beim Erstellen der Kontaktlinie 'ContactEntry createdContact = contactsService.Einfügen (URL, Kontakt); ' Ich habe folgenden Fehler: Ausführung der Anfrage fehlgeschlagen: https://www.google.com/m8/feeds/contacts/my-email%40gmail.com/full System.Net.WebException: HTTP-Fehler 401 nicht autorisiert bei System.Net.HttpWebRequest.GetResponse() bei Google.GData.Client.GDataRequest.Execute() ' Wie ich denke, ein Benutzername und ein Passwort sollte Service gegeben werden, aber wie? – AndreasU

+0

verwendeter Umfang: https://www.google.com/m8/feeds/contacts/my-email%40gmail.com/full – AndreasU