Google Contacts v3 API & OAuth v2, in Java

Cotheer picture Cotheer · Apr 30, 2013 · Viewed 7.7k times · Source

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

Answer

Cotheer picture Cotheer · May 1, 2013

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 :).