首页 > 解决方案 > 使用带有 API 密钥而不是 OAuth 的 Google Sheets Java API?

问题描述

有没有办法将“Google Sheet Java API”与 API 密钥一起使用,而不是在他们的示例中给出的 OAuth

https://developers.google.com/sheets/api/quickstart/java

我知道您可以使用 HTTP 请求通过 API 密钥获取数据,但我在想是否有办法使用 google 提供的 Java API 来执行此操作,这样我就不必为每个请求解析 JSON。

标签: javagoogle-sheetsgoogle-sheets-api

解决方案


我没有找到任何官方方法来实现这一点,但我能够按照Acquiring and using an API key中的描述做到这一点:

拥有 API 密钥后,您的应用程序可以将查询参数附加key=yourAPIKey到所有请求 URL。

通过使用请求拦截器并key手动添加查询参数,如下所示:

private Sheets getSheets() {
    NetHttpTransport transport = new NetHttpTransport.Builder().build();
    JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer httpRequestInitializer = request -> {
        request.setInterceptor(intercepted -> intercepted.getUrl().set("key", API_KEY));
    };

    return new Sheets.Builder(transport, jsonFactory, httpRequestInitializer)
            .setApplicationName(APPLICATION_NAME)
            .build();
}

public List<List<Object>> getValues(String spreadsheetId, String range) throws IOException {
    return getSheets()
            .spreadsheets()
            .values()
            .get(spreadsheetId, range)
            .execute()
            .getValues();
}

推荐阅读