Java and Google Spreadsheets API Authorization with OAuth 2.0

后端 未结 3 908
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 10:22

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 proc

相关标签:
3条回答
  • 2020-12-18 10:59

    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());
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-18 11:07

    [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.

    0 讨论(0)
  • 2020-12-18 11:15

    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
    0 讨论(0)
提交回复
热议问题