【问题标题】:Accessing Google Sheets from Spring MVC从 Spring MVC 访问 Google 表格
【发布时间】:2016-11-07 08:53:40
【问题描述】:

我正在尝试从我的后端访问 Google 表格,它是用 Spring MVC 编写的。使用教程我得到这样的东西:

public static Sheets getSheetsService() throws IOException {
    return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, authorize())
            .setApplicationName(APPLICATION_NAME)
            .build();
}

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

秘密的创建方式如下所述:https://developers.google.com/sheets/quickstart/java

这是“工作”,但应用程序的输出为我提供了一个链接。当我点击它时,我的浏览器会要求我选择一个 Google 帐户。如果我这样做一切正常,但我希望有一个更适合服务器的解决方案。我希望我的 secret.json 文件能够让我的应用程序在不提供我自己的用户帐户的情况下登录。有什么办法可以做到吗?

【问题讨论】:

  • 您可以尝试在使用OAuth 2.0 for Server to Server Applications 中查看服务帐户。您可以进行 API 调用,尤其是在调用 Cloud API 以访问基于项目的数据而不是特定于用户的数据时。
  • 你应该在生成credentials.json的时候选择了'Web server',这里有个地方放redirect url

标签: java google-sheets google-api google-sheets-api


【解决方案1】:

尝试使用 Gdata 3rd 方库而不是 google.v4。这是我用来传递凭据的代码。您必须创建一个 P12 文件 google's console

那么显然你的大部分工作表/工作簿读/写都必须改变以匹配 gdata 方法。

我希望这会有所帮助,如果没有,请提出任何问题,我也许可以提供帮助。

    // Application name
    private static final String APPLICATION_NAME = "spreadsheet-application-name";

    // account info and p12
    private static final String ACCOUNT_P12_ID = "P12@Account";
    private static File P12FILE;

    private static String ssName = "Spreadsheet name";
    private static String wsName = "worksheetname"; //this has to be all lower case for some reason

    // scopes
    private static final List<String> SCOPES = Arrays.asList(
            "https://docs.google.com/feeds",
            "https://spreadsheets.google.com/feeds");

    // Spreadsheet API URL
    private static final String SPREADSHEET_URL = "https://spreadsheets.google.com/feeds/spreadsheets/private/full";

    private static final URL SPREADSHEET_FEED_URL;

    static {
        try {
            SPREADSHEET_FEED_URL = new URL(SPREADSHEET_URL);
            P12FILE = getP12File();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }
    // Authorize-
    private static Credential authorize() throws Exception {

        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = new JacksonFactory();

        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountId(ACCOUNT_P12_ID)
                .setServiceAccountPrivateKeyFromP12File(P12FILE)
                .setServiceAccountScopes(SCOPES)
                .build();

//        boolean ret = credential.refreshToken();
        // debug dump
//        Log.debug("refreshToken:" + ret);

        // debug dump
//        if (credential != null) {
//            Log.debug("AccessToken:" + credential.getAccessToken());
//        }


        return credential;
    }

    //    Get service
    private static SpreadsheetService getService() throws Exception {

        SpreadsheetService service = new SpreadsheetService(APPLICATION_NAME);
        service.setProtocolVersion(SpreadsheetService.Versions.V3);

        Credential credential = authorize();
        service.setOAuth2Credentials(credential);

        // debug dump
//        Log.debug("Schema: " + service.getSchema().toString());
//        Log.debug("Protocol: " + service.getProtocolVersion().getVersionString());
//        Log.debug("Service Version: " + service.getServiceVersion());


        return service;
    }

   private static File getP12File(){
        ClassLoader classLoader = GoogleSheetsWriter.class.getClassLoader();
        return new File(classLoader.getResource("DriveAPITest-bf290e0ee314.p12").getFile());
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    相关资源
    最近更新 更多