通过服务器读取/写入Google表格而不使用OAuth

时间:2018-05-08 09:16:31

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

尝试通过互联网和google docs他们只提供OAuth方式。有没有办法用API Key读取/写入google工作表,而不是OAuth。

3 个答案:

答案 0 :(得分:1)

经过一些研究,来自google-oath-client模块的Credential对象可以提供帮助。从谷歌帐户下载.p12文件。用于在没有OAUth提示的情况下阅读Google工作表的代码。这也可用于编写或附加表格并进行一些修改:

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});
    }
}

答案 1 :(得分:0)

根据此documentation,当您的应用程序请求公共数据时,请求不需要授权,但需要附带标识符,例如API密钥。

  

您的应用程序发送到Google表格API的每个请求都需要向Google标识您的应用程序。有两种方法可以识别您的应用程序:使用OAuth 2.0令牌(也授权请求)和/或使用应用程序的API密钥。以下是如何确定使用哪些选项:

     
      
  • 如果请求需要授权(例如请求个人的私人数据),则应用程序必须为请求提供OAuth 2.0令牌。应用程序也可以提供API密钥,但不必提供。
  •   
  • 如果请求不需要授权(例如请求公共数据),则应用程序必须提供API密钥或OAuth 2.0令牌,或两者兼而有之 - 无论哪种选项对您来说都是最方便的。
  •   

但是,有些范围需要OAuth授权。请检查此链接:Access Google spreadsheet API without Oauth token

答案 2 :(得分:0)

使用API​​密钥,您可以从Google表格中 阅读 ,但前提是该表格与公众共享。

但是 到Google表格中,您必须OAuth。 See this link.