使用Google表格API和服务帐户时禁止使用403

时间:2016-08-22 04:23:36

标签: java oauth google-api google-oauth google-sheets-api

我有一个使用服务帐户的应用程序(因为它是从cron作业运行的,因此我无法通过浏览器中的用户进行授权)。以下是我创建工作表服务的方法:

private static final String APPLICATION_NAME = "my app";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static HttpTransport HTTP_TRANSPORT;

static {
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    } catch (GeneralSecurityException | IOException e) {
        e.printStackTrace();
    }
}

private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS);

private static Credential authorize() throws IOException, GeneralSecurityException {

    GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("key.json"), HTTP_TRANSPORT, JSON_FACTORY);
    credential = credential.createScoped(SCOPES);
    return credential;
}

static Sheets getSheetsService() throws IOException, GeneralSecurityException {
    Credential credential = authorize();

    return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
}

每次运行时,都会收到“com.google.api.client.googleapis.json.GoogleJsonResponseException:403 Forbidden”错误。有关如何解决此问题的想法吗?

0 个答案:

没有答案