How to use OAuth 2.0 authentication with Google’s GDATA Client Java Client Library

This article is for users who are using the Google Data Java Client Library (a.k.a. „gdata-java-client“) together with the Google API Client Library for Java (a.k.a. „google-api-java-client“).

For our app we started the  integration with Google Spreadsheets today and we were running into a problem related to authentication. The issue is that the Spreadsheet API is still based on the „older“ GDATA API but we wanted to to already use OAuth 2.0 for authentication which is part of Google’s new Client API for JAVA. Both APIs can co-exist besides each other as you can read in this migration guide.

The problem we faced was that the „older“ GDATA JAVA API for the SpreadSheet API has only methods for OAuth 1.0 or at least I wasn’t able to find any documentation and source code examples which showed how to use it with OAuth 2.0. I could only find examples of OAuth 1.0. The difference between OAuth 1.0 and OAuth 2.0 is that OAuth 2.0 only returns you an accessToken and rely fully on SSL, which frees you from signing and encryption stuff, while OAuth 1.0 returns you also a token_secret . In OAuth 1.0 you need to pass both things to each API call.

The problem was that the API does not seem to have any methods which only takes the accessToken. All methods I found require you to  pass things like OAuthParameters and OAuthSigner objects which are OAuth 1.0 related.
Thus the question was:
How can I tell my SpreadsheetService object to use my previously obtained OAuth 2.0 accessToken.

I found the solution a bit between the lines here. It says that you need can set a special HTTP-Header (Authorization: Bearer ACCESS_TOKEN)

Java Code Example:


SpreadsheetService service = new SpreadsheetService("yourAppName");
service.setHeader("Authorization", "Bearer " + accessToken);
URL metafeedUrl = new URL("");
SpreadsheetFeed feed = service.getFeed(metafeedUrl, SpreadsheetFeed.class);

List spreadsheets = feed.getEntries();
for (int i = 0; i < spreadsheets.size(); i++) {
SpreadsheetEntry entry = spreadsheets.get(i);
System.out.println("\t" + entry.getTitle().getPlainText());

Note: This code snippet assumes you received your accessToken using the new Google Java API as shown in this example.

After doing this the API call went through without problems and returned me a list of spreadsheets.

I hope that helps some people until google makes this more clear in their documentation or adds examples. Right now I found the documentation a bit confusion with all the different authentication mechanisms possible with the APIs. I also posted my solution here on StackOverflow.

Dieser Beitrag wurde unter Software-Development abgelegt und mit , , , , , , , verschlagwortet. Setze ein Lesezeichen auf den Permalink.