无法从服务帐户 com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden 访问谷歌表

时间:2021-05-20 13:46:57

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

我正在尝试使用 google sheet api 从 google sheet 读取数据。
GoogleSheetReader.java

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 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;
    
    public class GoogleSheetsReader {
    
        private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
        private static final String KEY_FILE_LOCATION = "*.p12";
        private static final String SERVICE_ACCOUNT_EMAIL = "email mentioned in 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);
        //private static final List<String> SCOPES = Collections.singletonList(GmailScopes.MAIL_GOOGLE_COM);
    
    
        /**
         * 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( 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();
        }
    
    
        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) {
                System.out.println("Some exception came over here");
                System.out.println(ex);
             //   LOGGER.error("Exception while reading google sheet", ex);
            } finally {
    
            }
            return null;
        }
    
        public static void main(String[] args) throws GeneralSecurityException, IOException {
            GoogleSheetsReader reader = new GoogleSheetsReader();
            reader.readSheet("testing sheats!A2:B", "1axHZNHiJ560B6z_l_S2PBKd0dBo0OLTB73YUNty4NEs", new int[]{0, 1});
        }
    }

我可以从我创建此服务帐户的帐户访问 Google 表格。但是使用这个响应是 回复

com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code": 403,
  "errors": [
    {
      "domain": "global",
      "message": "The caller does not have permission",
      "reason": "forbidden"
    }
  ],
  "message": "The caller does not have permission",
  "status": "PERMISSION_DENIED"
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.sheets</groupId>
  <artifactId>google-sheet-app</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>google-sheet-app</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client</artifactId>
      <version>1.23.0</version>
      <exclusions>
        <exclusion>
          <groupId>com.google.guava</groupId>
          <artifactId>guava-jdk5</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.google.gdata/core -->
    <dependency>
      <groupId>com.google.gdata</groupId>
      <artifactId>core</artifactId>
      <version>1.47.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>30.1.1-jre</version>
    </dependency>


    <dependency>
      <groupId>com.google.oauth-client</groupId>
      <artifactId>google-oauth-client-jetty</artifactId>
      <version>1.23.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-sheets</artifactId>
      <version>v4-rev493-1.23.0</version>
    </dependency>
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-lambda</artifactId>
      <version>1.11.163</version>
    </dependency>
    <dependency>
      <groupId>com.google.http-client</groupId>
      <artifactId>google-http-client-gson</artifactId>
      <version>1.34.2</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

我的 .p12 文件在下载文件夹中,所以我已经添加了完整路径。我已经应用了所有可能的解决方案,但仍然失败有人可以帮忙吗?

0 个答案:

没有答案