[Java] 구글드라이브API를 사용해 자바랑 연결하고 CRUD작업까지 -1

구준희·2023년 11월 15일
3
post-thumbnail

작업환경

  • SpringBoot
  • IntelliJ
  • GoogleDrive API
  • JAVA

Google Cloud 설정(중요!)

https://console.cloud.google.com/
여기 들어가서 로그인하고 프로젝트 생성까지 하기

이름까지 입력하고 만들기

방금 생성한 프로젝트 선택

배너 누르면 이 화면으로 오는데 여기서 API 및 서비스 누르기

API 및 서비스 사용설정 클릭

검색창에 googleDrive API 검색

Activity 말고 그냥 DriveAPI 누르기

사용 ㄱㄱ

기다리면 자동으로 이 화면으로 오는데 우측 상단에
사용자 인증 정보 만들기 클릭

완료 말고 다음 누르기

고유한 아이디 아무거나 입력하고 만들고 계속하기

중요!!
여기서 뷰어말고 소유자로 해야됨

여긴 안 적고 넘어가도 됨

왼쪽 사이드바에 사용자 인증 정보 누르면 이 화면와서

동의 화면 구성 클릭

외부 클릭하고 만들기

어차피 내부는 선택안됨

앱 이름은 아무거나 적고
이메일주소 선택하기

화면 내리면 개발자 연락처는 내 이메일주소 적고 저장 후 계속 클릭

저장 후 계속

테스트 앱이기 때문에 테스트 사용자를 추가 해야됨

여기에 추가된 사용자만 인증받고 사용할 수 있음

같이 프로젝트 하는 사람들이나 내 이메일주소 입력하기

추가하고 저장 후 계속

대시보드로 돌아가기

수정사항 생기면 앱 수정 눌러서 수정하면 됨

사용자 인증정보로 와서 OAuth 클라이언트 ID 클릭

유형 -> 데스크톱 앱
이름 -> 아무거나
적고 만들기

이런 팝업창 뜨는데 JSON 다운로드 클릭

그럼 파일 다운로드를 하는데 저 파일 이름을 credentials.json으로 바꿔주기

여기까지 했으면 기본 세팅은 끝

프로젝트 생성

여기에서 만들고 의존성 추가는 따로 안해줬음

압축풀고 프로젝트 열기

의존성 추가

//build.gradle
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'
implementation 'com.google.api-client:google-api-client:2.0.0'
implementation 'com.google.auth:google-auth-library-oauth2-http:1.11.0'
implementation 'com.google.code.gson:gson:2.9.1'

의존성 추가해준다음에 로드까지 해주기

클래스 생성

DriveQuickstart.java 파일 생성하기
MyApiApplication에 해도 상관은 없음

//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;
import java.util.Scanner;

public class DriveQuickstart {
    private static final String APPLICATION_NAME = "Google Drive API Java Quickstart";
    private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    //사용자의 토큰을 어디에 저장할지 경로를 지정
    private static final String TOKENS_DIRECTORY_PATH = "tokens";
    //어플리케이션이 요청하는 권한의 범위를 지정
    private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
    //비밀키 경로
    private static final String CREDENTIALS_FILE_PATH = "/credentials.json";

    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException{
        //credentials.json 파일을 in에 저장함
        InputStream in = DriveQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (in == null) {   // credentials이 빈값이면
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
        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(8080).build();
        Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
        return credential;
    }

    public static void main(String... args) throws GeneralSecurityException, IOException {
        String realFileId = "";
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();
        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());
            }
        }
    }
}

내 드라이브 안에 있는 파일 중에서 10개만 출력해주는 코드임

그리고 아까 다운로드 받은 credentials.json파일 resources폴더 안에 넣고 실행 ㄱㄱ

실행하면 이 화면 떠야됨

저 화면에서 Google Drive 파일 보기, 수정, 생성, 삭제 권한을 얻어와야되는데

그냥 파일 보기 이런식으로 권한을 제대로 못받아왔으면 망한거니깐 설정부터 다시해야됨

계속을 누르면 이 화면이 뜨는데 그냥 닫아버리면 됨

내 드라이브콘솔창

그리고 내 콘솔창에 저 목록들을 제대로 불러오면 설정까지 완벽하게 잘 된거임

다음편에 계속....

다음편보기

profile
꾸준히합니다.

1개의 댓글

comment-user-thumbnail
2024년 2월 3일

좋은 글 너무 잘봤습니다! 감사합니다

답글 달기