gpt4 book ai didi

java - 403 - 权限不足,无法使用 Java 将数据写入 Google 电子表格

转载 作者:行者123 更新时间:2023-12-02 08:41:35 25 4
gpt4 key购买 nike

我正在尝试使用 Java 编程语言将数据写入 Google 电子表格。我可以从工作表中读取数据,但无法将数据写入工作表。我总是得到"message": "请求的身份验证范围不足。",
“状态”:“PERMISSION_DENIED”
错误。我尝试将范围更改为 SPREADSHEETS, DRIVE 但没有解决问题。

这里是代码:

package io.com.google_sheet;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
import com.google.api.services.sheets.v4.model.AppendValuesResponse;
import com.google.api.services.sheets.v4.model.UpdateValuesResponse;
import com.google.api.services.sheets.v4.model.ValueRange;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SheetsQuickstart {
private static final String APPLICATION_NAME = "Google Sheet with Java";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";

/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
// private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS, SheetsScopes.DRIVE);
private static final List<String> SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS);

private static final String CREDENTIALS_FILE_PATH = "/credentials.json";

/**
* Creates an authorized Credential object.
* @param HTTP_TRANSPORT The network HTTP Transport.
* @return An authorized Credential object.
* @throws IOException If the credentials.json file cannot be found.
* @throws GeneralSecurityException
*/
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException, GeneralSecurityException {
// Load client secrets.
InputStream in = SheetsQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
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(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
// .setAccessType("offline")
// .build();
// LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
// return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");


GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");


}

public static void main(String... args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
final String spreadsheetId = "11ghLf1MnN4yedz5WYMCdV9tmaOu9G8B-R8DLm5fs-Io";//"1QF0uX9WFgA3L3zxOtFQbyHYWfvi88nzZiLrV6-LbavQ"; //"1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();

ValueRange value = new ValueRange()
.setValues(Arrays.asList(
Arrays.asList((Object)"Nikol", "Peter", "12:20")
));

try {
AppendValuesResponse appendData = service.spreadsheets().values()
.append(spreadsheetId, "Google Sheet with Java", value)
.setValueInputOption("USER_ENTERTED").setInsertDataOption("INSERT_ROWS")
.setIncludeValuesInResponse(true)
.execute();

System.out.println("Successfully entered data");
}
catch(Exception e) {
System.out.println("Could not add the data with error: " + e);
}
}
}

这是输出:

 Could not add the data with error: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Insufficient Permission",
"reason" : "insufficientPermissions"
} ],
"message" : "Request had insufficient authentication scopes.",
"status" : "PERMISSION_DENIED"
}

我在 Stackoverflow 和 Github 上看过类似的问题,但可以找到解决方案。

您能否检查一下我哪里出错了,以便我收到错误消息?

最佳答案

如果您在更新范围后不更新刷新 token (tokens 目录下的 StoredCredential 文件),这是一个常见错误。

您需要删除 StoredCredential 文件,运行应用程序,然后再次授予权限,这将生成具有更新范围的新 StoredCredential 文件。

关于java - 403 - 权限不足,无法使用 Java 将数据写入 Google 电子表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61353617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com