2016-07-27 28 views
1

Der folgende Code ist praktisch nur der QuickStart-Codebeispiel von Google Sheets Java API v4, aber für den Code für ein BatchUpdate, das ich aus einem anderen Post kopiert habe, um es zu testen; Ausführen des Codes gibt eine Ausnahme, die auf ein JSON-Objekt mit dem Text verweist:Google Sheets Java-API v4 BatchUpdate

„message“: „Anforderung nicht ausreichend Authentifizierungstive hatte“, „Grund“: „verbotenen“

als Der Code hat auf die Tabelle zugegriffen und Daten ohne Probleme bekommen. Ich verstehe nicht, wie die Berechtigungen fehlen, obwohl der Code, aus dem ich ihn kopiert habe, einen P12-Schlüssel anstelle der Datei client_secrets.json verwendet hat.

Jeder Zeiger wird geschätzt. Danke.

Code:

import com.google.api.client.auth.oauth2.Credential; 
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; 
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; 
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; 
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; 
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; 
import com.google.api.client.http.HttpTransport; 
import com.google.api.client.json.jackson2.JacksonFactory; 
import com.google.api.client.json.JsonFactory; 
import com.google.api.client.util.store.FileDataStoreFactory; 
import com.google.api.services.sheets.v4.SheetsScopes; 
import com.google.api.services.sheets.v4.model.*; 
import com.google.api.services.sheets.v4.Sheets; 

import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.Arrays; 
import java.util.ArrayList; 
import java.util.List; 

public class SheetsQuickstart { 
    /** Application name. */ 
    private static final String APPLICATION_NAME = 
     "Google Sheets API Java Quickstart"; 

    /** Directory to store user credentials for this application. */ 
    private static final java.io.File DATA_STORE_DIR = new java.io.File(
     System.getProperty("user.home"), ".credentials/sheets.googleapis.com-java-quickstart.json"); 

    /** Global instance of the {@link FileDataStoreFactory}. */ 
    private static FileDataStoreFactory DATA_STORE_FACTORY; 

    /** Global instance of the JSON factory. */ 
    private static final JsonFactory JSON_FACTORY = 
     JacksonFactory.getDefaultInstance(); 

    /** Global instance of the HTTP transport. */ 
    private static HttpTransport HTTP_TRANSPORT; 

    /** Global instance of the scopes required by this quickstart. 
    * 
    * If modifying these scopes, delete your previously saved credentials 
    * at ~/.credentials/sheets.googleapis.com-java-quickstart.json 
    */ 
    private static final List<String> SCOPES = 
     Arrays.asList(new String[]{ SheetsScopes.SPREADSHEETS}); 

    static { 
     try { 
      HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); 
      DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); 
     } catch (Throwable t) { 
      t.printStackTrace(); 
      System.exit(1); 
     } 
    } 

    /** 
    * Creates an authorized Credential object. 
    * @return an authorized Credential object. 
    * @throws IOException 
    */ 
    public static Credential authorize() throws IOException { 
     // Load client secrets. 
     InputStream in = 
      SheetsQuickstart.class.getResourceAsStream("/client_secret.json"); 
     GoogleClientSecrets clientSecrets = 
      GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); 

     // Build flow and trigger user authorization request. 
     GoogleAuthorizationCodeFlow.Builder authf = new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES); 
     for(String s: authf.getScopes()) System.out.println(s); 
     GoogleAuthorizationCodeFlow flow = authf 
       .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; 
    } 

    /** 
    * Build and return an authorized Sheets API client service. 
    * @return an authorized Sheets API client service 
    * @throws IOException 
    */ 
    public static Sheets getSheetsService() throws IOException { 
     Credential credential = authorize(); 
     return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) 
       .setApplicationName(APPLICATION_NAME) 
       .build(); 
    } 

    public static void main(String[] args) throws IOException { 
     // Build a new authorized API client service. 

     Sheets service = getSheetsService(); 

     String spsId   = "1bvToosbxMkt40FUyOjNCXdIP8N_LAZrBz_CwkloLx8g"; 
     Spreadsheet sh = service.spreadsheets().get(spsId).execute(); 

     ValueRange rsp = service.spreadsheets().values().get(spsId, "A1:B").execute(); 

     List<List<Object>> vls = rsp.getValues(); 
     if (vls == null || vls.size() == 0) { 
      System.out.println("No data found."); 
     } else { 
      for (List row : vls) { 
      // Print columns A and E, which correspond to indices 0 and 4. 
      if(row.size() > 1) 
      System.out.println(row.get(0) + " " + row.get(1)); 
      } 
     } 

     List<ValueRange> oList = new ArrayList<>(); 
     oList.add(vr); 

     List<RowData> rowData = new ArrayList<RowData>(); 

     CellData cell = new CellData(); 
     cell.setUserEnteredValue(new ExtendedValue().setStringValue("3355")); 

     List<CellData> cellData = new ArrayList<CellData>(); 
     cellData.add(cell); 
     rowData.add(new RowData().setValues(cellData)); 

     BatchUpdateSpreadsheetRequest batchRequests = new BatchUpdateSpreadsheetRequest(); 
     BatchUpdateSpreadsheetResponse response; 

     AppendCellsRequest aCR = new AppendCellsRequest(); 
     List<Request> requests = new ArrayList<Request>(); 
     requests.add(new Request().setAppendCells(aCR)); 
     batchRequests.setRequests(requests); 

     response= service.spreadsheets().batchUpdate(spsId, batchRequests).execute(); 
    } 
} 
+0

Gestern habe ich vergessen zu überprüfen, dass es enthalten war. – Mathkute

Antwort

0

Bitte versuchen Umfang Informationen, die den Anforderungen Ihrer Anwendung hinzuzufügen.

Wie in Method: spreadsheets.batchUpdate erwähnt, eine der folgenden OAuth-Bereiche benötigt:

  • https://www.googleapis.com/auth/drive
  • https://www.googleapis.com/auth/spreadsheets

verfügbar OAuth 2.0 Bereichsinformationen für die API von Google Tabellen aufgeführt sind, in Authorizing requests with OAuth 2.0 und Abgesehen davon könnte auch die Lösung in diesem SO nach - Google spreadsheet api Request had insufficient authentication scopes helfen.

+0

Ich habe bereits diese Antwort gelesen, die mit der Lösung in drei Teilen (http://stackoverflow.com/questions/37520782/write-to-googlesheet-via-api-with-java): das Problem sieht aus wie die Detail, dass ich mich um die Sheet-Autorisierung kümmern musste: Es gibt zwei Autorisierungsstufen und ich habe dieses Detail übersehen, als ich die Berechtigungen für das Spreadsheet änderte: Danke, dass du es mir gezeigt hast: jetzt funktioniert der Code korrekt. – Mathkute

Verwandte Themen