javagoogle-app-enginegoogle-apigoogle-api-java-clientuserinfo

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


I have a Java ClientRequest to the Google API that returns a JSON containing the profile based on 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": "myemail@gmail.com",
    "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 want to use the Java library to avoid mounting the HTTP request, keep the google server URL, and other minor things.
2 I don't need the authorization 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 not to go there. So far only found examples using the Plus library.

In summary, I need something in the google API Java library precisely equivalent to the HTTP request I use nowadays.

Thank you very much in advance!


Solution

  • 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();