Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
149 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...