Google 使用 OAuth 2.0 从电子表格中获取数据

Using OAuth 2.0 for Google to fetch Data from a Spreadsheet

我正在尝试编写一个从电子表格中读取数据的程序。我知道我必须使用 OAuth 或 API 密钥,但是我完全不知道如何在我的程序中实现这样的系统。我环顾四周,发现了很多示例和 "tutorials",但是我没有找到任何示例。(我对编程还比较陌生)。 那么有人能以最简单的方式向我解释我是如何实现一个系统来验证我的程序的,这样我就可以从电子表格中读取数据(只有授权部分,其余部分我想我已经明白了)。 如果这是相关的,可以制作电子表格 public,它只是一列数据。我正在使用 Eclipse 作为我的环境。

此致

按照此 Java Quickstart 中指示的步骤进行操作。

第 1 步:打开 Google 表格 API

一个。使用此向导在 Google Developers Console 中创建或 select 项目并自动打开 API。单击继续,然后转到凭据。

b。在“将凭据添加到您的项目”页面上,单击“取消”按钮。

c。在页面顶部,select OAuth 同意屏幕选项卡。 Select 电子邮件地址,如果尚未设置,请输入产品名称,然后单击“保存”按钮。

d. Select 凭据选项卡,单击创建凭据按钮和 select OAuth 客户端 ID。

e。 Select 应用程序类型为其他,输入名称"Google Sheets API Quickstart",然后单击创建按钮。

f。单击“确定”关闭出现的对话框。

克。单击客户端 ID 右侧的 file_download(下载 JSON)按钮。

小时。将此文件移动到您的工作目录并将其重命名为 client_secret.json.

当所有设置完成后,这就是使用您下载的 client_secret.json 处理授权的代码。

public static Credential authorize() throws IOException {
        // Load client secrets.
        InputStream in =
            SheetsQuickstart.class.getResourceAsStream("/client_secret.json");
        GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow.Builder(
                        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(DATA_STORE_FACTORY)
                .setAccessType("offline")
                .build();
        Credential credential = new AuthorizationCodeInstalledApp(
            flow, new LocalServerReceiver()).authorize("user");
        System.out.println(
                "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
        return credential;
    }