2016-07-27 5 views
1

다음 코드는 실질적으로 Google 스프레드 시트 Java API v4 QuickStart 코드 샘플이지만 다른 게시물에서 복사 한 BatchUpdate 코드를위한 코드입니다.Google 스프레드 시트 Java API v4 일괄 업데이트

"메시지": 코드를 실행하면 텍스트 등, JSON 객체를 참조 예외가 있습니다. "요청이 불충분 한 인증 범위를했다"를 "이유": "금지"

등을 코드가 문제없이 데이터를 얻는 스프레드 시트에 액세스했습니다. 코드를 복사 한 후에 client_secrets.json 파일 대신 P12 키를 사용했지만 권한이 누락 된 것을 이해하지 못합니다.

모든 포인터는 높이 평가됩니다. 감사합니다.

코드 :

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

어제 내가 포함되어 있는지 확인하는 것을 잊어 버렸습니다. – Mathkute

답변

0

하는 응용 프로그램에 필요한 범위 정보를 추가 해보세요.

Method: spreadsheets.batchUpdate에서 언급 한 바와 같이, 다음의 OAuth 범위 중 하나가 필요합니다 구글 시트 API에 대한

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

사용할 수의 OAuth 2.0 범위 정보가 Authorizing requests with OAuth 2.0에 나열되고 그 외에도,이 게시물에 주어진 해결책 - Google spreadsheet api Request had insufficient authentication scopes도 도움이 될 수 있습니다.

+0

나는 그 답변을 이미 읽었습니다. 세 부분으로 구성된 해결책을 가지고 있습니다. (http://stackoverflow.com/questions/37520782/write-to-googlesheet-via-api-with-java) : 문제는 시트 권한 부여를 처리해야하는 세부 정보 : 두 가지 권한 등급이 있으며 스프레드 시트에 대한 권한을 변경할 때 그 내용을 놓쳤습니다. 저를 가리켜 주셔서 감사합니다. 이제 코드가 올바르게 작동합니다. – Mathkute

관련 문제