Reputation: 103
I am using java library for oauth2 authentication for accessing google spreadsheet.
I am using below code for OAuth2 authentication:
credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setTokenServerEncodedUrl("https://accounts.google.com/o/oauth2/token")
.setServiceAccountScopes("https://www.googleapis.com/auth/drive", "https://spreadsheets.google.com/feeds", "https://docs.google.com/feeds")
.setServiceAccountPrivateKeyFromP12File(new File("xxxxx-privatekey.p12")).build();
After getting "credential", using below code to read spreadsheet:
SpreadsheetService service = new SpreadsheetService(
"MySpreadsheetIntegration");
service.setOAuth2Credentials(credential);
URL SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
System.out.println(feed.getTotalResults());
Executing above code give me back total result 0.
If I use:
service.setUserCredentials("email", "password");
in place of oauth2 authentication, it gives me back correct results. Not sure what is wrong with the OAuth2 authentication. Also when I print "access token" from "credential" object it prints a valid access token.
Upvotes: 4
Views: 2969
Reputation: 3700
I use:
spreadsheetService = new SpreadsheetService("cellmaster.com.au-v0.2");
spreadsheetService.setHeader("Authorization", "Bearer " + accessToken);
rather than:
spreadsheetService = new SpreadsheetService("cellmaster.com.au-v0.2");
spreadsheetService.setOAuth2Credentials(credential);
also I had to add code for the refresh token. As the access token soon expires. But the refresh token works as you would expect.
Upvotes: 2