Java 使用Google Sheets Api时出错

Java 使用Google Sheets Api时出错,java,google-api,google-sheets,Java,Google Api,Google Sheets,你好!目前有两种方法可以获得第一个凭证,即该凭证是否能够正常使用Google Drive Api,并首次要求获得许可证: private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); private static HttpTransport HTTP_TRANSPORT; private static FileDataStoreFactory DAT

你好!目前有两种方法可以获得第一个凭证,即该凭证是否能够正常使用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();
    }
私有静态最终JsonFactory JSON_工厂=
JacksonFactory.getDefaultInstance();
专用静态HttpTransport HTTP_传输;
私有静态文件数据存储工厂数据存储工厂;
private static final java.io.File DATA_STORE_DIR=new java.io.File(
System.getProperty(“user.home”),“.credentials/drive\u quickstart”);
私有静态最终列表作用域=
Arrays.asList(DriveScopes.DRIVE\u元数据\u只读);
静止的{
试一试{
HTTP_TRANSPORT=GoogleNetHttpTransport.newTrustedTransport();
DATA\u STORE\u FACTORY=新文件datastorefactory(DATA\u STORE\u DIR);
}捕获(可丢弃的t){
t、 printStackTrace();
系统出口(1);
}
}
公共静态凭据授权()引发IOException{
//加载客户端机密。
输入流输入=
DriveQuickstart.class.getResourceAsStream(“/client_secret.json”);
谷歌客户机密=
load(JSON_工厂,新的InputStreamReader(in));
//生成流并触发用户授权请求。
GoogleAuthorizationCodeFlow=
新的GoogleAuthorizationCodeFlow.Builder(
HTTP_传输、JSON_工厂、客户端机密、作用域)
.setDataStoreFactory(数据存储工厂)
.setAccessType(“脱机”)
.build();
凭证凭证=新授权代码已安装App(
流,新的LocalServerReceiver())。授权(“用户”);
System.out.println(
“凭证保存到”+数据存储\目录getAbsolutePath());
返回凭证;
}
/**
*生成并返回授权驱动器客户端服务。
*@返回授权驱动器客户端服务
*@抛出异常
*/
公共静态驱动器getDriveService()引发IOException{
凭证=授权();
返回新的驱动器生成器(
HTTP_传输、JSON_工厂、凭证)
.setApplicationName(应用程序名称)
.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());
            }
        }
Drive service=getDriveService();
//打印最多10个文件的名称和ID。
FileList结果=service.files().list()
.setPageSize(100)
.setFields(“nextPageToken,文件(id,名称)”)
.execute();
List files=result.getFiles();
如果(files==null | | files.size()==0){
System.out.println(“未找到文件”);
}否则{
System.out.println(“文件:”);
用于(文件:文件){
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());
        }
InputStream-in=
DriveQuickstart.class.getResourceAsStream(“/client_secret.json”);
谷歌客户机密=
load(JSON_工厂,新的InputStreamReader(in));
GoogleAuthorizationCodeFlow=
新的GoogleAuthorizationCodeFlow.Builder(
HTTP_传输、JSON_工厂、客户端机密、作用域)
.setDataStoreFactory(数据存储工厂)
.setAccessType(“脱机”)
.build();
凭证凭证=新授权代码已安装App(
流,新的LocalServerReceiver())。授权(“用户”);
System.out.println(
“\”凭证保存到“+数据存储\目录getAbsolutePath());
电子表格服务=新的电子表格服务(“MyAppName”);
服务。设置OAuth2Credentials(凭证);
URL电子表格\u提要\u URL=新URL(
"https://spreadsheets.google.com/feeds/spreadsheets/private/full");
SpreadsheetFeed=service.getFeed(电子表格\u feed\u URL,SpreadsheetFeed.class);
列表电子表格=feed.getEntries();
用于(电子表格输入电子表格:电子表格){
System.out.println(电子表格.getTitle().getPlainText()+“”+电子表格.getId());
}
但事实证明,当您创建电子表格提要错误的实例时:

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)
线程“main”com.google.gdata.client.GoogleService$SessionExpiredException中的异常:令牌无效-AuthSub令牌的作用域错误 令牌无效-AuthSub令牌的作用域错误 令牌无效-AuthSub令牌的作用域错误 错误401 位于com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:570) 位于com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560) 位于com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538) 位于com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536) 位于com.google.gdata.client.Service.getFeed(Service.java:1135) 位于com.google.gdata.client.Service.getFeed(Service.java:998) 位于com.google.gdata.client.GoogleService.getFeed(GoogleService.java:652) 位于com.google.gdata.client.Service.getFeed(Service.java:1017) 位于TestAuthAndSheets.main(TestAuthAndSheets.java:71)
请告诉我,问题出在哪里?还有一种通过其他方式获取凭据的方法,但每次不合适的O代码都需要手动操作。

错误消息会准确地告诉您问题出在哪里。驱动器令牌的作用域错误。
private static final List SCOPES=Arrays.asLi