使用带有OAuth2的Google电子表格API

时间:2015-06-02 09:25:16

标签: oauth-2.0 google-sheets gdata google-spreadsheet-api google-api-java-client

由于Google已弃用OAuth1,我尝试将我的应用程序迁移到OAuth2。我正在使用服务帐户并尝试阅读Google电子表格。我能够获取访问令牌,但仍然无法获取与我的帐户关联的电子表格。我正在使用的代码,请让我知道我在哪里犯了错误。 :

HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
        String SPREADSHEET_URL = "https://spreadsheets.google.com/feeds/spreadsheets/private/full";
        URL SPREADSHEET_FEED_URL = new URL(SPREADSHEET_URL);
        String[] SCOPESArray = { "https://spreadsheets.google.com/feeds" };
        final List SCOPES = Arrays.asList(SCOPESArray);

        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountId("28031770151-826a7iuekrsmr0gf4kc####iiop@developer.gserviceaccount.com")
                .setServiceAccountScopes(SCOPES).setServiceAccountPrivateKeyFromP12File(new File("key.p12"))
                .build();

        System.out.println(credential.getAccessToken());
        credential.refreshToken();
        credential.getRefreshToken();
        SpreadsheetService service = new SpreadsheetService("inlaid-chassis-9640");
        service.setOAuth2Credentials(credential);
        SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
        List<SpreadsheetEntry> spreadsheets = feed.getEntries();

//电子表格出来是一个空白数组

1 个答案:

答案 0 :(得分:1)

解决!为此,我们需要与https://console.developers.google.com上创建项目时生成的服务帐户ID /电子邮件ID(请参阅上面的代码)共享我们的电子表格。