Google Contact API (ошибка информации заголовка проверки подлинности)

Я новичок в Google Contact Api. я пытаюсь получить все свои контакты с помощью Google Contact API. Для этого я использовал аутентификацию Oauth и Google Contact API.

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import com.google.gdata.client.Query;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.authn.oauth.OAuthParameters.OAuthType;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.Link;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.contacts.GroupMembershipInfo;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.ExtendedProperty;
import com.google.gdata.data.extensions.Im;
import com.google.gdata.data.extensions.Name;
import com.google.gdata.util.ServiceException;

public class GoogleContactsAccess{


  /*  This method will authenticate the user credentials passed to it and      returns an instance of ContactService class.*/

 public ContactsService authenticateId(){

    GoogleOAuthParameters oAuthParameters = null;
    ContactsService contactService = null;

    try{
        contactService = new ContactsService("API Project");
        oAuthParameters = new GoogleOAuthParameters();
        oAuthParameters.setOAuthConsumerKey("ConsumerKey");
        oAuthParameters.setOAuthConsumerSecret("ConsumerKey");
        oAuthParameters.setScope("https://www.google.com/m8/feeds");
        oAuthParameters.setOAuthType(OAuthType.TWO_LEGGED_OAUTH);
        oAuthParameters.addCustomBaseParameter("xoauth_requestor_id", "my [email protected]");
        contactService.setOAuthCredentials(oAuthParameters,new OAuthHmacSha1Signer());
        contactService.getRequestFactory().setHeader("GData-Version", "3.0");
    }catch(Exception e){
        e.printStackTrace();
    }
    return contactService;

}

/* This method will print details of all the contacts available in that particular Google account. */

 public void printAllContacts(ContactsService myService)throws ServiceException, IOException {

    // Request the feed
    URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full?v=3.0&alt=json'");

 // The query that will retrieve all contacts
    Query myQuery = new Query(feedUrl);

    ContactFeed resultFeed = myService.getFeed(myQuery, ContactFeed.class);

    // Print the results
    System.out.println(resultFeed.getTitle().getPlainText());
    for (int i = 0; i < resultFeed.getEntries().size(); i++) {
        ContactEntry entry = resultFeed.getEntries().get(i);
        if (entry.hasName()) {
            Name name = entry.getName();
            if (name.hasFullName()) {
                String fullNameToDisplay = name.getFullName().getValue();
                if (name.getFullName().hasYomi()) {
                    fullNameToDisplay += " (" + name.getFullName().getYomi() + ")";
                }
                System.out.println("\t\t" + fullNameToDisplay);
            } else {
                System.out.println("\t\t (no full name found)");
            }

            if (name.hasNamePrefix()) {
                System.out.println("\t\t" + name.getNamePrefix().getValue());
            } else {
                System.out.println("\t\t (no name prefix found)");
            }
            if (name.hasGivenName()) {
                String givenNameToDisplay = name.getGivenName().getValue();
                if (name.getGivenName().hasYomi()) {
                    givenNameToDisplay += " (" + name.getGivenName().getYomi() + ")";
                }
                System.out.println("\t\t" + givenNameToDisplay);
            } else {
                System.out.println("\t\t (no given name found)");
            }

            if (name.hasAdditionalName()) {
                String additionalNameToDisplay = name.getAdditionalName().getValue();
                if (name.getAdditionalName().hasYomi()) {
                    additionalNameToDisplay += " (" + name.getAdditionalName().getYomi() + ")";
                }
                System.out.println("\t\t" + additionalNameToDisplay);
            } else {
                System.out.println("\t\t (no additional name found)");
            }

            if (name.hasFamilyName()) {
                String familyNameToDisplay = name.getFamilyName().getValue();
                if (name.getFamilyName().hasYomi()) {
                    familyNameToDisplay += " (" + name.getFamilyName().getYomi() + ")";
                }
                System.out.println("\t\t" + familyNameToDisplay);
            } else {
                System.out.println("\t\t (no family name found)");
            }

            if (name.hasNameSuffix()) {
                System.out.println("\t\t" + name.getNameSuffix().getValue());
            } else {
                System.out.println("\t\t (no name suffix found)");
            }

        } else {
            System.out.println("\t (no name found)");
        }

        System.out.println("Email addresses:");

        for (Email email : entry.getEmailAddresses()) {

            System.out.print(" " + email.getAddress());
            if (email.getRel() != null) {
                System.out.print(" rel:" + email.getRel());
            }
            if (email.getLabel() != null) {
                System.out.print(" label:" + email.getLabel());
            }
            if (email.getPrimary()) {
                System.out.print(" (primary) ");
            }
            System.out.print("\n");

        }

        System.out.println("IM addresses:");
        for (Im im : entry.getImAddresses()) {

            System.out.print(" " + im.getAddress());
            if (im.getLabel() != null) {
                System.out.print(" label:" + im.getLabel());
            }
            if (im.getRel() != null) {
                System.out.print(" rel:" + im.getRel());
            }
            if (im.getProtocol() != null) {
                System.out.print(" protocol:" + im.getProtocol());
            }
            if (im.getPrimary()) {
                System.out.print(" (primary) ");
            }
            System.out.print("\n");

        }

        System.out.println("Groups:");
        for (GroupMembershipInfo group : entry.getGroupMembershipInfos()) {
            String groupHref = group.getHref();
            System.out.println("  Id: " + groupHref);
        }

        System.out.println("Extended Properties:");
        for (ExtendedProperty property : entry.getExtendedProperties()) {

            if (property.getValue() != null) {
                System.out.println("  " + property.getName() + "(value) = " +
                        property.getValue());
            } else if (property.getXmlBlob() != null) {
                System.out.println("  " + property.getName() + "(xmlBlob)= " +
                        property.getXmlBlob().getBlob());
            }

        }

        Link photoLink = entry.getContactPhotoLink();
        String photoLinkHref = photoLink.getHref();
        System.out.println("Photo Link: " + photoLinkHref);

        if (photoLink.getEtag() != null) {
            System.out.println("Contact Photo's ETag: " + photoLink.getEtag());
        }

        System.out.println("Contact's ETag: " + entry.getEtag());
    }
}

public static void main(String args[]){
    try {
        GoogleContactsAccess googleContactsAccess = new GoogleContactsAccess();

        ContactsService contactSrv = googleContactsAccess.authenticateId();

        googleContactsAccess.printAllContacts(contactSrv);

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }catch (Exception ex) {
        ex.printStackTrace();
    }
}

}

я попробовал приведенный выше код. я получаю следующее исключение

java.lang.NullPointerException: нет информации заголовка аутентификации в com.google.gdata.util.AuthenticationException.initFromAuthHeader(AuthenticationException.java:96) в com.google.gdata.util.AuthenticationException.(AuthenticationException.java:67) в com. google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:608) по адресу com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:564) по адресу com.google.gdata.client.http. HttpGDataRequest.checkResponse(HttpGDataRequest.java:560) в com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538) в com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java: 536) в com.google.gdata.client.Service.getFeed(Service.java:1135) в com.google.gdata.client.Service.getFeed(Service.java:1077) в com.google.gdata.client.GoogleService .getFeed(GoogleService.java:676) на com.google.gdata.client .Service.getFeed(Service.java:1034) по адресу com.cohere.getcontacts.GoogleContactsAccess.printAllContacts(GoogleContactsAccess.java:59) по адресу com.cohere.getcontacts.GoogleContactsAccess.main(GoogleContactsAccess.java:197)

так что кто-нибудь поможет мне решить проблему заранее спасибо


person Manikandan G    schedule 13.07.2015    source источник


Ответы (1)


Похоже, вы используете ConsumerKey в качестве ключа и секрета в своем коде:

oAuthParameters.setOAuthConsumerKey("ConsumerKey");
oAuthParameters.setOAuthConsumerSecret("ConsumerKey");

Вам нужно использовать правильный ConsumerSecret вашего приложения.

person amishra    schedule 13.07.2015
comment
нет, я использовал свой идентификатор клиента консоли Google API и секрет клиента - person Manikandan G; 14.07.2015