How to get user profile on Google API using the JAVA library?

augustocosta picture augustocosta · Mar 19, 2014 · Viewed 8.6k times · Source

I have a Java ClientRequest to the Google API that returns a json containing the profile based in an access_token. The URL is:
https://www.googleapis.com/oauth2/v1/userinfo?access_token=ya29.1.AADtN_VALuuUTBm8ENfNTz8s...

And the response is:

{
    "id": "111223344556677889900",
    "email": "[email protected]",
    "verified_email": true,
    "name": "My Name",
    "given_name": "My",
    "family_name": "Name",
    "link": "plus.google.com/111223344556677889900",
    "picture": "photo.jpg",
    "gender": "male",
    "locale": "en"
}

Some points:

1 I'd like to use the java library to avoid mount the http request, keep the google server url and another minor things.
2 I don't need the authorization's steps because at this point my method receives the access token (all the oauth steps are done before).
3 In this method we don't have (and so far don't need) the client id and secret.
4 I don't need the Google+ scope. Actually I prefer don't go there. So far only found examples using the Plus library.

In summary I need something in the google api java library exactly equivalent to the http request used nowadays.

Thank you very much in advance!

Answer

aswin picture aswin · Mar 27, 2014

I hope this helps

GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);   
 Oauth2 oauth2 = new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), credential).setApplicationName(
          "Oauth2").build();
 Userinfoplus userinfo = oauth2.userinfo().get().execute();
 userinfo.toPrettyString();