구글 드라이브 API 연동 (Java)

hwhyeons·2023년 2월 3일
0

업로드 & 다운로드 기능

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.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.FileContent;
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.*;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;


/**
 * 액세스 거부 오류 :  관리자 권한으로 실행
 * 기타 권한 오류 : StoredCredentials 삭제
 */
/* class to demonstarte 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.
     *
     * 여기 권한을 수정해야 파일 읽기만 할건지 쓰기말한거지 등등을 결정할 수 있고,
     * 매번 토큰 새로 처리하는게 아니라 StoredToken이 저장되기 때문에 tokens폴더에 있는 StoredCredential를 삭제해줘야함
     */
//    private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE_METADATA_READONLY);
    private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
    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());
            }
        }
//
        System.out.println("\n\n업로드 시작..");
        File fileMetaData = new File();
        fileMetaData.setName("uploadtest.txt"); // 업로드할 파일
        java.io.File f = new java.io.File("uploadtest.txt");
        // 따로 정해진 타입이 없으면 application/octet-stream (바이너리 데이터)
        FileContent fileContent = new FileContent("text/plain",f);
        service.files().create(fileMetaData,fileContent).execute();


        String downFileName = "1.zip";
        System.out.println("\n\n다운로드 시작..");
        try {
            File downloadFile = files.stream().filter(downFile->downFile.getName().equals(downFileName)).findAny().orElseThrow(()->new FileNotFoundException(downFileName+"은 존재하지 않는 파일입니다"));
            String downloadFileId = downloadFile.getId();
            OutputStream outputStream = new ByteArrayOutputStream();
            service.files().get(downloadFileId)
                    .executeMediaAndDownloadTo(outputStream);
            var byteArrayOutputStream = (ByteArrayOutputStream) outputStream;
            try(OutputStream writeStream = new FileOutputStream(downFileName)) {
                byteArrayOutputStream.writeTo(writeStream);
            }
        } catch (GoogleJsonResponseException e) {
            // TODO(developer) - handle error appropriately
            System.err.println("Unable to move file: " + e.getDetails());
            throw e;
        }



    }
}

업로드 / 다운로드 가능

파일을 업로드 할 때, FileContent 생성할 때, 파일 형식에 따라

인자를 수정해줘야함


사용자 인증 방식 : 로컬에 json 파일 저장

출처 : 링크

2개의 댓글

comment-user-thumbnail
2023년 2월 20일

안녕하세요
저는 Gmai을 연동해서 쓰려고하는데
Please open the following address in your browser:
주소
첫 인증 후 tomcat에 StoredCredential이 저장되는데
1~2시간 지나면 계속 인증을 요구하는데 어디가 잘못된부분일까요 ..
올려주신 코드에서 드라이브코드를 제외하고 모든코드가 동일합니다!

1개의 답글