从Spring MVC访问Google表格

时间:2016-11-07 08:53:40

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

我正试图从我的后端访问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文件使我的应用程序能够登录而不提供我自己的用户帐户。有没有办法让这项工作?

1 个答案:

答案 0 :(得分:0)

尝试使用Gdata第三方库而不是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());
    }