问题
I want to access a spreadsheet on Google Drive by using de java Google spreadsheet API. In the past i used the client login method to login but this method is deprecated now. Now I'm trying to use a service account to getting authenticated without interaction with the user because the tool is running in the background i needs to be automated. But i can't get it working. These my code now.
List<String> SCOPES_ARRAY = Arrays.asList(
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
"https://docs.google.com/feeds",
"https://spreadsheets.google.com/feeds");
credential = new GoogleCredential.Builder()
.setTransport(transport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(
"xxxxxx@developer.gserviceaccount.com")
.setServiceAccountScopes(SCOPES_ARRAY)
.setServiceAccountPrivateKeyFromP12File(p12)
.setServiceAccountUser("me@gmail.com")
.build();
service = new SpreadsheetService("MonitorV3");
service.setOAuth2Credentials(credential);
SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
worksheetFeed = service.getFeed(spreadsheet.getWorksheetFeedUrl(),
WorksheetFeed.class);
But i'm getting a nullpointerexception when executing the last line. something goes wrong with refresh token. Is there someone seeing what i'm doing wrong?

I made a standalone simple application and now I get following detailded error:
Exception in thread "main" com.google.gdata.util.AuthenticationException: Failed to refresh access token: 401 Unauthorized
at com.google.gdata.client.GoogleAuthTokenFactory$OAuth2Token.refreshToken(GoogleAuthTokenFactory.java:260)
at com.google.gdata.client.GoogleAuthTokenFactory.handleSessionExpiredException(GoogleAuthTokenFactory.java:702)
at com.google.gdata.client.GoogleService.handleSessionExpiredException(GoogleService.java:738)
at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:649)
at com.google.gdata.client.Service.getFeed(Service.java:1017)
at JavaApplication20.printDocuments(JavaApplication20.java:50)
at main.main(main.java:35)
回答1:
I fixed this by using following code:
credential = new GoogleCredential.Builder()
.setTransport(transport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("618982716759-9ele96d95b7gqar6tn2ofa7jrjrudlol@developer.gserviceaccount.com")
.setServiceAccountPrivateKeyFromP12File(p12)
.setServiceAccountScopes(SCOPES_ARRAY).build();
credential.refreshToken();
So without the .setServiceAccountUser("me@gmail.com"). Now it's working without any errors.
回答2:
Another approach to access Google Sheets with Google Service account is:
InputStream inputStream = getAssets().open("service_account_key.json"); // put your service account's key.json file in asset folder.
GoogleCredential googleCredential = GoogleCredential.fromStream(inputStream)
.createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS_READONLY));
Important points to note here that:
- You should write your block of code to access Google Sheets in a Thread or Async call.
If you get any exception like android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork, then please include these lines before making Async call:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .permitAll().build(); StrictMode.setThreadPolicy(policy);
Please refer below documentations for detailed explanation:
https://developers.google.com/sheets/quickstart/android?hl=es-419#step_5_setup_the_sample https://developers.google.com/identity/protocols/OAuth2ServiceAccount#authorizingrequests
Happy Androiding.
来源:https://stackoverflow.com/questions/31287911/google-spreadsheet-with-a-service-account