자바 빠른 시작

빠른 시작에서는 Google Workspace API를 호출하는 앱을 설정하고 실행하는 방법을 설명합니다.

Google Workspace 빠른 시작은 API 클라이언트 라이브러리를 사용하여 인증 및 승인 흐름의 일부 세부정보를 처리합니다. 자체 앱에는 클라이언트 라이브러리를 사용하는 것이 좋습니다. 이 빠른 시작에서는 테스트 환경에 적합한 간소화된 인증 방식을 사용합니다. 프로덕션 환경의 경우 앱에 적합한 액세스 사용자 인증 정보를 선택하기 전에 인증 및 승인에 대해 알아보는 것이 좋습니다.

Google Drive API에 요청하는 Java 명령줄 애플리케이션을 만듭니다.

목표

  • 환경을 설정합니다.
  • 샘플을 설정합니다.
  • 샘플을 실행합니다.

기본 요건

  • Google Drive가 사용 설정된 Google 계정

환경 설정하기

이 빠른 시작을 완료하려면 환경을 설정하세요.

API 사용 설정

Google API를 사용하려면 먼저 Google Cloud 프로젝트에서 사용 설정해야 합니다. 단일 Google Cloud 프로젝트에서 하나 이상의 API를 사용 설정할 수 있습니다.
  • Google Cloud 콘솔에서 Google Drive API를 사용 설정합니다.

    API 사용 설정

새 Google Cloud 프로젝트를 사용하여 이 빠른 시작을 완료하는 경우 OAuth 동의 화면을 구성하고 자신을 테스트 사용자로 추가합니다. Cloud 프로젝트에서 이 단계를 이미 완료했다면 다음 섹션으로 건너뛰세요.

  1. Google Cloud 콘솔에서 메뉴 > API 및 서비스 > OAuth 동의 화면으로 이동합니다.

    OAuth 동의 화면으로 이동

  2. 앱의 사용자 유형을 선택한 다음 만들기를 클릭합니다.
  3. 앱 등록 양식을 작성한 다음 저장하고 계속하기를 클릭합니다.
  4. 지금은 범위 추가를 건너뛰고 저장 후 계속을 클릭해도 됩니다. 앞으로 Google Workspace 조직 외부에서 사용할 앱을 만들 때는 앱에 필요한 승인 범위를 추가하고 확인해야 합니다.

  5. 사용자 유형으로 외부를 선택한 경우 테스트 사용자를 추가합니다.
    1. 테스트 사용자에서 사용자 추가를 클릭합니다.
    2. 이메일 주소 및 승인된 다른 테스트 사용자를 입력한 다음 저장하고 계속하기를 클릭합니다.
  6. 앱 등록 요약을 검토합니다. 변경하려면 수정을 클릭합니다. 앱 등록이 확인되면 대시보드로 돌아가기를 클릭합니다.

데스크톱 애플리케이션에 대한 사용자 인증 정보 승인

앱에서 최종 사용자를 인증하고 사용자 데이터에 액세스하려면 OAuth 2.0 클라이언트 ID를 하나 이상 만들어야 합니다. 클라이언트 ID는 Google OAuth 서버에서 단일 앱을 식별하는 데 사용됩니다. 앱이 여러 플랫폼에서 실행되는 경우 플랫폼마다 별도의 클라이언트 ID를 만들어야 합니다.
  1. Google Cloud 콘솔에서 메뉴 > API 및 서비스 > 사용자 인증 정보로 이동합니다.

    사용자 인증 정보로 이동

  2. 사용자 인증 정보 만들기 > OAuth 클라이언트 ID를 클릭합니다.
  3. 애플리케이션 유형 > 데스크톱 앱을 클릭합니다.
  4. 이름 입력란에 사용자 인증 정보의 이름을 입력합니다. 이 이름은 Google Cloud 콘솔에만 표시됩니다.
  5. 만들기를 클릭합니다. OAuth 클라이언트 생성 완료 화면이 나타나 새 클라이언트 ID와 클라이언트 비밀번호를 표시합니다.
  6. OK(확인)를 클릭합니다. 새로 만든 사용자 인증 정보가 OAuth 2.0 클라이언트 ID 아래에 표시됩니다.
  7. 다운로드한 JSON 파일을 credentials.json로 저장하고 작업 디렉터리로 파일을 이동합니다.

작업공간 준비하기

  1. 작업 디렉터리에서 새 프로젝트 구조를 만듭니다.

    gradle init --type basic
    mkdir -p src/main/java src/main/resources 
    
  2. src/main/resources/ 디렉터리에서 이전에 다운로드한 credentials.json 파일을 복사합니다.

  3. 기본 build.gradle 파일을 열고 콘텐츠를 다음 코드로 바꿉니다.

    drive/quickstart/build.gradle
    apply plugin: 'java'
    apply plugin: 'application'
    
    mainClassName = 'DriveQuickstart'
    sourceCompatibility = 11
    targetCompatibility = 11
    version = '1.0'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation 'com.google.api-client:google-api-client:2.0.0'
        implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1'
        implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0'
    }
    

샘플 설정

  1. src/main/java/ 디렉터리에서 build.gradle 파일의 mainClassName 값과 일치하는 이름으로 새 자바 파일을 만듭니다.

  2. 새 Java 파일에 다음 코드를 포함합니다.

    drive/quickstart/src/main/java/DriveQuickstart.java
    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.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.client.util.store.FileDataStoreFactory;
    import com.google.api.services.drive.Drive;
    import com.google.api.services.drive.DriveScopes;
    import com.google.api.services.drive.model.File;
    import com.google.api.services.drive.model.FileList;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.security.GeneralSecurityException;
    import java.util.Collections;
    import java.util.List;
    
    /* class to demonstrate use of Drive files list API */
    public class DriveQuickstart {
      /**
       * Application name.
       */
      private static final String APPLICATION_NAME = "Google Drive API Java Quickstart";
      /**
       * Global instance of the JSON factory.
       */
      private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
      /**
       * Directory to store authorization tokens for this application.
       */
      private static final String TOKENS_DIRECTORY_PATH = "tokens";
    
      /**
       * Global instance of the scopes required by this quickstart.
       * If modifying these scopes, delete your previously saved tokens/ folder.
       */
      private static final List<String> SCOPES =
          Collections.singletonList(DriveScopes.DRIVE_METADATA_READONLY);
      private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
    
      /**
       * Creates an authorized Credential object.
       *
       * @param HTTP_TRANSPORT The network HTTP Transport.
       * @return An authorized Credential object.
       * @throws IOException If the credentials.json file cannot be found.
       */
      private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT)
          throws IOException {
        // Load client secrets.
        InputStream in = DriveQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (in == null) {
          throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
    
        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
        Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
        //returns an authorized Credential object.
        return credential;
      }
    
      public static void main(String... args) throws IOException, GeneralSecurityException {
        // Build a new authorized API client service.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build();
    
        // Print the names and IDs for up to 10 files.
        FileList result = service.files().list()
            .setPageSize(10)
            .setFields("nextPageToken, files(id, name)")
            .execute();
        List<File> files = result.getFiles();
        if (files == null || files.isEmpty()) {
          System.out.println("No files found.");
        } else {
          System.out.println("Files:");
          for (File file : files) {
            System.out.printf("%s (%s)\n", file.getName(), file.getId());
          }
        }
      }
    }

샘플 실행

  1. 샘플을 실행합니다.

    gradle run
    
  1. 샘플을 처음 실행하면 액세스를 승인하라는 메시지가 표시됩니다.
    1. 아직 Google 계정에 로그인하지 않은 경우 메시지가 표시될 때 로그인합니다. 여러 계정에 로그인되어 있는 경우 승인에 사용할 계정을 하나 선택하세요.
    2. 동의를 클릭합니다.

    Java 애플리케이션이 실행되고 Google Drive API를 호출합니다.

    승인 정보는 파일 시스템에 저장되므로 다음에 샘플 코드를 실행할 때는 승인하라는 메시지가 표시되지 않습니다.

다음 단계