Java/YouTube Data API

Java YouTube Data API v3 인증하는 법

ddss6565 2021. 6. 5. 09:20

https://console.developers.google.com

 

Google Cloud Platform

하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을 사용하려면 로그인하세요.

accounts.google.com

1. 선행작업

YouTube Data API v3 사용 등록, OAuth 2.0 세팅, client_secret.json 받기

 

implementation group: 'com.google.apis', name: 'google-api-services-youtube', version: 'v3-rev222-1.25.0'
implementation group: 'com.google.oauth-client', name: 'google-oauth-client-jetty', version: '1.31.5'

implementation group: 'commons-io', name: 'commons-io', version: '2.8.0'
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'
implementation group: 'org.apache.commons', name: 'commons-collections4', version: '4.4'

 

private HttpTransport httpTransport;
private DataStoreFactory dataStoreFactory;
private YouTube youTube;
private JsonFactory JSON_FACTORY = new JacksonFactory();

private String oauthCredentialsPath = ".oauth-credentials";
private String clientSecretPath = "client_secret.json";

public static void main(String[] args)
{
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    dataStoreFactory = new FileDataStoreFactory(new File(oauthCredentialsPath));
    
    Credential credential = authorize();
    youTube = new YouTube.Builder(httpTransport, JSON_FACTORY, credential).build();
}

public Credential authorize() throws Exception
{
    ClassPathResource resource = new ClassPathResource(clientSecretPath);
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(resource.getInputStream()));
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets,
            Collections.singleton(YouTubeScopes.YOUTUBE)).setDataStoreFactory(dataStoreFactory).build();

    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver.Builder().setPort(80).build()).authorize("user");
}

이후 커맨드창에 출력된 주소를 웹브라우저를 통해 열면 인증시작

인증후에는 youTube 객체를 사용하시면 됩니다.

반응형