0

I want to implement Google Sheet API request using service account. I created this code:

HttpTransport httpTransport = new NetHttpTransport(); JacksonFactory JSON_FACTORY = new JacksonFactory(); ClassLoader classLoader = this.getClass().getClassLoader(); java.io.File path = new java.io.File(classLoader.getResource("i-6dc0c917ee63.p12").getFile()); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountId("[email protected]") .setServiceAccountPrivateKeyFromP12File(path) .setServiceAccountScopes(Arrays.asList(SheetsScopes.SPREADSHEETS)) .setServiceAccountUser("[email protected]") .build(); Sheets service = new Sheets.Builder(httpTransport, JSON_FACTORY, null) .setApplicationName("project") .setHttpRequestInitializer(credential).build(); Sheets.Spreadsheets spreadsheets = service.spreadsheets(); Spreadsheet includeGridData = spreadsheets.get(spreadsheetId).execute(); 

But I get this error:

com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized

at this method .execute();

Do you know how I can fix this issue?

2 Answers 2

1

I was having the same issue and it was driving me insane. I had 2 different copies of the same app, using the same credentials.json, but I'd get a successful response in one, but a 401 unauthorized in the other. I finally solved it by deleting the StoredCredential. So next time I ran my app I was taken to Google's authentication page, and it worked.

TLDR: delete StoredCredential One way to find it is running find . -name 'StoredCredential' from the root of your application.

Sign up to request clarification or add additional context in comments.

Comments

0

Based from Standard Error Responses, an error 401 is due to invalidCredentials and this indicates that the auth token is invalid or has expired.

Recommended Action:

Do not retry without fixing the problem. You need to get a new auth token.

With this, you may want to check Token Expiration which mentioned that you must write your code to anticipate the possibility that a granted token might no longer work. It also gives these possible reasons why a token might stop working:

  • The user has revoked access.
  • The token has not been used for six months.
  • The user changed passwords and the token contains Gmail scopes.
  • The user account has exceeded a certain number of token requests.

Hope that helps!

2 Comments

I tested to refresh the token before each call but the result is the same.
You may want to check solution given in this SO post wherein there are given steps to do if the token is invalid.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.