Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception in thread "main" com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized

I tried the example given here.

https://developers.google.com/sheets/quickstart/java

Its giving me this exception -

Exception in thread "main" com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.auth.oauth2.Credential.executeRefreshToken(Credential.java:570)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:868)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at SheetsQuickstart.main(SheetsQuickstart.java:106)

I have given all the necessary permission to it.

I am using sheet api version v4

Update -

If i am passing email id in the example instead of user then its is giving me this response.

Changes -

public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in =
        SheetsQuickstart.class.getResourceAsStream("/client_secret.json");
    GoogleClientSecrets clientSecrets =
        GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(
                    HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(DATA_STORE_FACTORY)
            .setAccessType("offline")
            .build();
    //Changed Part.
    Credential credential = new AuthorizationCodeInstalledApp(
        flow, new LocalServerReceiver()).authorize("[email protected]");
    System.out.println(
            "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    return credential;
}

Response -

Name, Major
Alexandra, English
Andrew, Math
Anna, English
Becky, Art
Benjamin, English
Carl, Art
Carrie, English
Dorothy, Math
Dylan, Math
Edward, English
Ellen, Physics
Fiona, Art
John, Physics
Jonathan, Math
Joseph, English
Josephine, Math
Karen, English
Kevin, Physics
Lisa, Art
Mary, Physics
Maureen, Physics
Nick, Art
Olivia, Physics
Pamela, Math
Patrick, Art
Robert, English
Sean, Physics
Stacy, Math
Thomas, Art
Will, Math

I got the further help from this link to resolve 400 - Unable to parse range: Class Data!A2:A4"

400 Bad Request Resolution

like image 550
Java_Alert Avatar asked Oct 18 '22 02:10

Java_Alert


1 Answers

First, make sure you follow properly the steps in the quickstart guide especially by enabling the Sheets API in your Developers Console.

Now for the Error TokenResponseException: 401 Unauthorized, based from this thread, the common causes for that error when making API calls with an access token are:

  • expired access token (most common)

  • Developer accidentally disabled the APIs (uncommon)

  • User revokes token (rare)

Sometimes, more explanation exists in the response body of a HTTP 4xx. In the Java client, for example, you should log the error, because it will assist in troubleshooting:

try {   
       // Make your Google API call
} catch (GoogleJsonResponseException e) {
      GoogleJsonError error = e.getDetails();
      // Print out the message and errors
}

You could take your existing code and make an API call here whenever you get a HTTP 4xx and log that response. This’ll return some useful information.

If the token is invalid, you can follow this steps.

  1. Remove the access token from your datastore or database.
  2. Use the refresh token to acquire a new access token (if you are using a refresh token)
  3. Try to make the API call again. If it works, you’re good! If not …
  4. Check the access token against the tokenInfo API
  5. If it’s still invalid, do a full reauth

For more information, you can check this related SO question.

like image 160
KENdi Avatar answered Oct 21 '22 04:10

KENdi