【问题标题】:Google Sheets requesting access to a users sheets for public sheetGoogle 表格请求访问公共表格的用户表格
【发布时间】:2021-01-16 19:58:56
【问题描述】:

我正在开发一个 Java 应用程序,该应用程序将连接并从公开的 google 表格中读取数据。 当应用程序第一次运行时,它会询问用户是否有权访问他们的谷歌表格。该应用不会从用户自己的工作表中读取任何内容,只会从公共工作表中读取任何内容,因此不知道如何停止询问。

我正在使用

请求数据
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    InputStream in = GoogleAPI.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");
}

public ArrayList<Template> loadTemplates() throws IOException, GeneralSecurityException {
    ArrayList<Template> templateList = new ArrayList();
    // Build a new authorized API client service.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    final String spreadsheetId = "****";
    final String range = "****";
    Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build();
    ValueRange response = service.spreadsheets().values()
            .get(spreadsheetId, range)
            .execute();
    List<List<Object>> values = response.getValues();
    if (values == null || values.isEmpty()) {
        System.out.println("No data found.");
    } else {
        for (List row : values) {
            / /Code here
        }
    }
    return templateList;
}

【问题讨论】:

    标签: java google-sheets-api


    【解决方案1】:

    将其切换为使用 API 而不是我只读过的 oAuth。

    在方法中添加了以下内容。

    HttpRequestInitializer httpRequestInitializer = request -> {
            request.setInterceptor(intercepted -> intercepted.getUrl().set("key", API_KEY));
        };
        Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, httpRequestInitializer)
                .setApplicationName(APPLICATION_NAME)
                .build();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-24
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 2011-03-27
      • 2019-02-28
      • 1970-01-01
      • 2016-10-24
      相关资源
      最近更新 更多