gpt4 book ai didi

java - 使用 Google Sheets Api 时出错

转载 作者:行者123 更新时间:2023-11-30 07:38:42 25 4
gpt4 key购买 nike

美好的一天!手头有两种方法可以获取第一个 Credential,以便与 Google Drive Api 正常工作,并首次请求许可:

private static final JsonFactory JSON_FACTORY =
JacksonFactory.getDefaultInstance();
private static HttpTransport HTTP_TRANSPORT;
private static FileDataStoreFactory DATA_STORE_FACTORY;
private static final java.io.File DATA_STORE_DIR = new java.io.File(
System.getProperty("user.home"), ".credentials/drive_quickstart");
private static final List<String> SCOPES =
Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY);


static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}

public static Credential authorize() throws IOException {
// Load client secrets.
InputStream in =
DriveQuickstart.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;
}

/**
* Build and return an authorized Drive client service.
* @return an authorized Drive client service
* @throws IOException
*/
public static Drive getDriveService() throws IOException {
Credential credential = authorize();
return new Drive.Builder(
HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}

然后我使用这些方法来获取我可用的文档列表

Drive service = getDriveService();

// Print the names and IDs for up to 10 files.
FileList result = service.files().list()
.setPageSize(100)
.setFields("nextPageToken, files(id, name)")
.execute();
List<File> files = result.getFiles();
if (files == null || files.size() == 0) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
}
}

它工作正常且正确,但我需要进一步直接使用表格(Google Sheets Api)进行类推,生成凭据并将可用表格列表带到控制台:

InputStream in =
DriveQuickstart.class.getResourceAsStream("/client_secret.json");
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

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());

SpreadsheetService service = new SpreadsheetService("MyAppName");
service.setOAuth2Credentials(credential);

URL SPREADSHEET_FEED_URL = new URL(
"https://spreadsheets.google.com/feeds/spreadsheets/private/full");

SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();

for (SpreadsheetEntry spreadsheet : spreadsheets) {
System.out.println(spreadsheet.getTitle().getPlainText() + " " + spreadsheet.getId());
}

但事实证明,当您创建 Spreadsheet Feed 实例时出现错误:

Exception in thread "main" com.google.gdata.client.GoogleService$SessionExpiredException: Token invalid - AuthSub token has wrong scope
<HTML>
<HEAD>
<TITLE>Token invalid - AuthSub token has wrong scope</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Token invalid - AuthSub token has wrong scope</H1>
<H2>Error 401</H2>
</BODY>
</HTML>

at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:570)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536)
at com.google.gdata.client.Service.getFeed(Service.java:1135)
at com.google.gdata.client.Service.getFeed(Service.java:998)
at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:652)
at com.google.gdata.client.Service.getFeed(Service.java:1017)
at TestAuthAndSheets.main(TestAuthAndSheets.java:71)

请告诉我,问题出在哪里?还有一种通过其他方式获取Credentials的方法,但是需要每次都手工O代码,不太适合。

最佳答案

错误消息准确地告诉您问题所在。驱动器 token 的范围错误。 private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY);仅请求访问范围 DRIVE_METADATA_READONLY,这足以查看文件,但不使用 Sheets api。您要查找的是添加 SheetsScopes.SPREADSHEETS到范围列表 (SCOPES)。

关于java - 使用 Google Sheets Api 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34995879/

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