Java and Google Spreadsheets API Authorization wit

2019-01-25 21:19发布

问题:

I want to read Google Spreadsheets using Java, and the recommended way to do this is using the Google Spreadsheets API.

The problem begins when you want to make procedures secure, so they encourage you to use OAuth 2.0. In the official page they show how to do this using only .NET and say that "the Java client library doesn't currently support OAuth 2.0", and they give alternatives like using OAuth 1.0 or Client Login using directly email and password.

Is this for sure?, isn't there a way to do OAuth 2.0 Authentication through Java, maybe not using directly the Java client library, but through requests with specific parameters.

Please I would appreciate any suggestions.

回答1:

The Google Data Java Client Library now supports OAuth 2.0:

https://code.google.com/p/gdata-java-client/source/detail?r=505

Unfortunately, there are no complete samples in the library showing how to use it. I'd recommend checking these two links to put together the information to make it work:

  • https://code.google.com/p/google-oauth-java-client/wiki/OAuth2
  • https://code.google.com/p/google-api-java-client/wiki/OAuth2


回答2:

I also found it quite silly that the developer docs provided Java examples for everything except OAuth2. Here's some sample code that I used to get it working. For completeness it includes the retrieving spreadsheets example in the later section. Note also that you have to add the required scopes to the Java DrEdit example as shown below.

public class GSpreadsheets {

    private static final String CLIENT_ID = "YOUR_CLIENT_ID";
    private static final String CLIENT_SECRET = "YOUR_SECRET_ID";
    private static final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";

    public static void main(String[] args) throws Exception {

        if (CLIENT_ID.equals("YOUR_CLIENT_ID") || CLIENT_SECRET.equals("YOUR_SECRET_ID")) {
            throw new RuntimeException(
                    "TODO: Get client ID and SECRET from https://cloud.google.com/console");
        }

            // get credentials similar to Java DrEdit example
            // https://developers.google.com/drive/examples/java
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
                Arrays.asList(DriveScopes.DRIVE, 
                              "https://spreadsheets.google.com/feeds", 
                              "https://docs.google.com/feeds"))
                .setAccessType("online")
                .setApprovalPrompt("auto").build();

        String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
        System.out.println("Please open the following URL in your "
                + "browser then type the authorization code:");
        System.out.println("  " + url);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String code = br.readLine();

        GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
        GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

            // create the service and pass it the credentials you created earlier
        SpreadsheetService service = new SpreadsheetService("MyAppNameHere");
        service.setOAuth2Credentials(credential);

        // Define the URL to request.  This should never change.
        URL SPREADSHEET_FEED_URL = new URL(
            "https://spreadsheets.google.com/feeds/spreadsheets/private/full");

        // Make a request to the API and get all spreadsheets.
        SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
        List<SpreadsheetEntry> spreadsheets = feed.getEntries();

        // Iterate through all of the spreadsheets returned
        for (SpreadsheetEntry spreadsheet : spreadsheets) {
          // Print the title of this spreadsheet to the screen
          System.out.println(spreadsheet.getTitle().getPlainText());
        }
    }
}


回答3:

[Edit]

Java OAuth2 code

Blog post on [google-spreadsheet-api] and OAuth2, with code
http://soatutorials.blogspot.co.at/2013/08/google-spreadsheet-api-connecting-with.html

Related question: OAuth2 authorization from Java/Scala using google gdata client API

[end edit]

I used: Google drive DrEdit tutorial, full example shows how to use OAuth 2.0 with Drive. The code works with google spreadsheets GData style API. (note: does not include refresh token, but the refresh token works as you would expect, so not hard too add.) -

Extra Note: A better documented API is Google-Apps-Script.