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?
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:
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:
Hope that helps!