按照此Java Quickstart 中指示的步骤进行操作。
第 1 步:开启 Google Sheets API
一个。使用此向导在 Google Developers Console 中创建或选择一个项目并自动打开 API。单击继续,然后转到凭据。
b.在将凭据添加到您的项目页面上,单击取消按钮。
c。在页面顶部,选择 OAuth 同意屏幕选项卡。选择一个电子邮件地址,输入产品名称(如果尚未设置),然后单击“保存”按钮。
d。选择凭据选项卡,单击创建凭据按钮并选择 OAuth 客户端 ID。
e。选择应用类型Other,输入名称“Google Sheets API Quickstart”,点击创建按钮。
f。单击“确定”关闭生成的对话框。
g.单击客户端 ID 右侧的 file_download(下载 JSON)按钮。
h。将此文件移动到您的工作目录并将其重命名为 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;
}