Read/Write Google sheet 通过服务器而不使用 OAuth

Read/Write Google sheet via Server without using OAuth

尝试通过互联网,google docs他们只提供 OAuth 方式。有没有一种方法可以使用 API 密钥而不是 OAuth read/write 到 google 工作表。

据此documentation,当您的应用程序请求public数据时,该请求不需要授权,但需要附有标识符,例如API键。

Every request your application sends to the Google Sheets API needs to identify your application to Google. There are two ways to identify your application: using an OAuth 2.0 token (which also authorizes the request) and/or using the application's API key. Here's how to determine which of those options to use:

  • If the request requires authorization (such as a request for an individual's private data), then the application must provide an OAuth 2.0 token with the request. The application may also provide the API key, but it doesn't have to.
  • If the request doesn't require authorization (such as a request for public data), then the application must provide either the API key or an OAuth 2.0 token, or both—whatever option is most convenient for you.

但是,有些范围需要 OAuth 授权。检查此 link:.

经过一些研究,google-oath-client 模块中的 Credential 对象可以提供帮助。从 google 帐户下载 .p12 文件。下面没有 OAUth 提示的情况下读取 google sheet 的代码。这也可以用于编写或附加 sheets 并进行一些修改:

package com.mycomp;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
import com.google.api.services.sheets.v4.model.ValueRange;
import com.nm.vernacular.services.SpreadSheetsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by ankushgupta & modified for SO.
 */

public class GoogleSheetsReader {

    private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    private static final String KEY_FILE_LOCATION = "<Name of p12 file>.p12";
    private static final String SERVICE_ACCOUNT_EMAIL = "<email of google service account>";
    private static final String APPLICATION_NAME = "Google Sheets API";

    private static final Logger LOGGER = LoggerFactory.getLogger(GoogleSheetsReader.class);

    /**
     * Global instance of the scopes required by this quickstart.
     * If modifying these scopes, delete your previously saved credentials/ folder.
     */
    private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS);

    /**
     * Creates an authorized Credential object.
     * @return An authorized Credential object.
     * @throws IOException If there is no client_secret.
     */
    private Credential getCredentials() throws URISyntaxException, IOException, GeneralSecurityException {
        //Reading Key File
        URL fileURL = GoogleSheetsReader.class.getClassLoader().getResource(KEY_FILE_LOCATION);
        // Initializes an authorized analytics service object.
        if(fileURL==null) {
            fileURL = (new File("/resources/"+ KEY_FILE_LOCATION)).toURI().toURL();
        }
        // Construct a GoogleCredential object with the service account email
        // and p12 file downloaded from the developer console.
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        return new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountPrivateKeyFromP12File(new File(fileURL.toURI()))
                .setServiceAccountScopes(SCOPES)
                .build();
    }

    @Override
    public List<Object[]> readSheet(String nameAndRange, String key, int[] returnRange) throws GeneralSecurityException, IOException {
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        final String spreadsheetId = key;
        final String range = nameAndRange;
        try {
            Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials())
                    .setApplicationName(APPLICATION_NAME)
                    .build();

            ValueRange response = service.spreadsheets().values()
                    .get(spreadsheetId, range)
                    .execute();
            List<List<Object>> values = response.getValues();

            int a = returnRange.length;
            List<Object[]> result = new LinkedList<>();

            if (values == null || values.isEmpty()) {
                return Collections.emptyList();
            } else {
                for (List row : values) {
                    if(row.size() >= a) {
                        Object[] objArr = new Object[a];
                        for(int i=0;i<a;i++) {
                            objArr[i] = row.get(returnRange[i]);
                        }
                        result.add(objArr);
                    }
                }
            }
            return result;
        } catch(Exception ex) {
            LOGGER.error("Exception while reading google sheet", ex);
        } finally {

        }
        return null;
    }

    public static void main(String[] args) {
     GoogleSheetsReader reader = new GoogleSheetsReader();
     reader.readSheet("<Sheet Name>!A2:B", "<sheets key from URL>", new int[]{0, 1});
    }
}

使用 API 键,您可以 从 google sheet 中读取 ,但是仅当 sheet 与 public 共享时。

但是要到googlesheets,你必须OAuth。