9

For the last few days i've been trying to get a list of google contacts using the above APIs. Needles to say, unsuccessfully. Google documentation (which is a total mess if i may say) has not been very helpful regarding my problem. The thing is, i have no idea how to authorize the ContactsService object using OAuth v2 API. I've already downloaded Google OAuth2.0 library which, again, has no proper documentation and/or no proper examples for total beginners like myself.

So to sum it up, does anyone have any working "Hello world" type of examples or any kind of "guidance" for the above problem?

As a side note, i did managed to get the contacts using the Scribe API, but as you may know, the response is in the xml/json format which needs to be parsed first and that's not what i want.

Thank you

Kara
  • 6,115
  • 16
  • 50
  • 57
Cotheer
  • 191
  • 3
  • 7

2 Answers2

9

It seems i have finally made some progress. The problem, apparently, was that there are bunch of different OAuth2 libraries out there, some of them are either deprecated or just won't work with Contacts v3, that is, generated access token will be invalid (that's what i concluded).

So for authorization and generating access token i've used Google API Client 1.14.1 (beta), and my code is as follows:

Servlet 1 (generating auth URL):

protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");           

        GoogleAuthorizationCodeRequestUrl authorizationCodeURL=new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URL, SCOPES);

        authorizationCodeURL.setAccessType("offline");//For future compatibility

        String authorizationURL=authorizationCodeURL.build();
        System.out.println("AUTHORIZATION URL: "+authorizationURL); 

        response.sendRedirect(new URL(authorizationURL).toString());

}

Servlet 2 (dealing with access token)

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();


    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet SignInFinished</title>");
    out.println("</head>");
    out.println("<body>");


    HttpTransport transport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    GoogleAuthorizationCodeTokenRequest authorizationTokenRequest = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET, request.getParameter("code"), REDIRECT_URL);

    GoogleTokenResponse tokenResponse = authorizationTokenRequest.execute();

    out.println("OAuth2 Access Token: " + tokenResponse.getAccessToken());

    GoogleCredential gc = new GoogleCredential();
    gc.setAccessToken(tokenResponse.getAccessToken());

    ContactsService contactsService = new ContactsService("Lasso Project");
    contactsService.setOAuth2Credentials(gc);

    try {
        URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");

        Query myQuery = new Query(feedUrl);
        myQuery.setMaxResults(1000);

        ContactFeed resultFeed = contactsService.query(myQuery, ContactFeed.class);

        for (int i = 0; i < resultFeed.getEntries().size(); i++) {
            out.println(resultFeed.getEntries().get(i).getTitle().getPlainText() + "<br/>");
        }

    } catch (Exception e) {
        System.out.println(e);
    }

    out.println("</body>");
    out.println("</html>");
}

NOTE: If you are using Client ID for Web Applications, REDIRECT_URL must be one of Redirect URLs you entered when registering application via Google console.

Well, I hope this'll be helpful to some of you :).

Cotheer
  • 191
  • 3
  • 7
  • Thank you very much. After a lot of failed attempts to get this working, I finally got it with your help! – Moshe Shaham Sep 24 '14 at 11:40
  • Cotheer sir can u tell me the version of jar's you have used for contact service – Vartika Feb 10 '15 at 06:42
  • Great example. Thank you so much. It's so frustrating working with this API, so many different versions and approaches. Yours is the simples and closest to what I needed. Really apreciate. – Cesar Zapata Dec 01 '15 at 18:34
0

I had trouble as well trying to retrieve google contacts. With OAuth2.0, you first need to get an access token. Then it gets easy, you can request for the id of the group you are looking for :

import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.contacts.ContactGroupEntry;
import com.google.gdata.data.contacts.ContactGroupFeed;

private static final String GROUPS_URL = "https://www.google.com/m8/feeds/groups/default/full";

private int getIdOfMyGroup() {
    ContactsService contactsService = new ContactsService("MY_PRODUCT_NAME");
    contactsService.setHeader("Authorization", "Bearer " + MY_ACCESS_TOKEN);

    try {
        URL feedUrl = new URL(GROUPS_URL);
        ContactGroupFeed resultFeed = contactsService.getFeed(feedUrl, ContactGroupFeed.class);
        // "My Contacts" group id will always be the first one in the answer
        ContactGroupEntry entry = resultFeed.getEntries().get(0);

        return entry.getId();
    } catch (...) { ... }
}

Eventually you will be able with the group id to request its contacts :

private static final String CONTACTS_URL = "https://www.google.com/m8/feeds/contacts/default/full";
private static final int MAX_NB_CONTACTS = 1000;

private List<ContactEntry> getContacts() {
    ContactsService contactsService = new ContactsService("MY_PRODUCT_NAME");
    contactsService.setHeader("Authorization", "Bearer " + MY_ACCESS_TOKEN);

    try {
        URL feedUrl = new URL(CONTACTS_URL);
        Query myQuery = new Query(feedUrl);
                    // to retrieve contacts of the group I found just above
        myQuery.setStringCustomParameter("group", group);
        myQuery.setMaxResults(MAX_NB_CONTACTS);
        ContactFeed resultFeed = contactsService.query(myQuery, ContactFeed.class);
        List<ContactEntry> contactEntries = resultFeed.getEntries();

        return contactEntries;
    } catch (...) { ... }
}
itsu
  • 222
  • 1
  • 10
  • Already tried this method, and just like before, the query/getFeed method throws an exception: `java.lang.NullPointerException: No authentication header information` – Cotheer Apr 30 '13 at 12:41
  • It worked for me. I guess your problem come from the OAuth part. Are you sure your acess token is valid ? – itsu Apr 30 '13 at 12:54
  • I get the access token, is it valid, not sure there is a way to check that. :S. – Cotheer Apr 30 '13 at 13:01
  • For a [webservice](https://developers.google.com/accounts/docs/OAuth2WebServer?hl=fr) for example, you get something like that { "access_token":"1/fFAGRNJru1FTz70BzhT3Zg", "expires_in":3920, "token_type":"Bearer" } for a valid access token. I don't know what kind of project you are developing on but it should not be hard to check wether your access token is correct or not – itsu Apr 30 '13 at 13:25
  • It's a java web application. Using 2 servlets, one for initializing the auth process and the other one as a callback servlet in which i get the access token. Using `GoogleOAuthParameters` for setting the parameters and `GoogleOAuthHelper` for generating the auth url. I'd paste my code here but there is limit to how many chars i can enter. – Cotheer Apr 30 '13 at 13:36
  • how to get access token any help? – Vartika Feb 05 '15 at 07:57