비버놀로지

[Youtube API 유튜브] 3. Spring boot 에서 Youtube API (Java) 본문

OPEN API 활용

[Youtube API 유튜브] 3. Spring boot 에서 Youtube API (Java)

KUNDUZ 2021. 4. 16. 16:22
728x90

developers.google.com/youtube/v3/code_samples?hl=ko

 

코드 예  |  YouTube Data API  |  Google Developers

[{ "type": "thumb-down", "id": "missingTheInformationINeed", "label":"필요한 정보가 없음" },{ "type": "thumb-down", "id": "tooComplicatedTooManySteps", "label":"너무 복잡함/단계 수가 너무 많음" },{ "type": "thumb-down", "id": "outOfDat

developers.google.com

위의 링크를 참고해서 Spring boot에 활용했다.

 

(1) pom.xml 환경 설정

 

아래의 코드를 pom.xml에 추가해주어 youtube api를 활용할 수 있게 한다.

  <repositories>
    <repository>
      <id>google-api-services</id>
      <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
    </repository>
  </repositories>

  <dependencies>
    <!-- YouTube Data V3 support -->
    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-youtube</artifactId>
      <version>${project.youtube.version}</version>
    </dependency>

    <dependency>
      <groupId>com.google.http-client</groupId>
      <artifactId>google-http-client-jackson2</artifactId>
      <version>${project.http.version}</version>
    </dependency>
  </dependencies>

(2) library 호출

 

아래와 같은 library를 import를 해서 youtube api를 활용한다.

 

import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.ResourceId;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;

 

(3) build 객체 생성

youtube 객체를 생성해 준다.

youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {
	public void initialize(HttpRequest request) 
    throws IOException {
	}})
    .setApplicationName("youtube-cmdline-search-sample")
    .build();

(4) search 객체 생성

아래에 setKey에 앞서 발급받은 api key를 입력해 주고, setQ에 검색할 키워드를 입력해 search 객체를 생성해 준다.

SearchListResponse searchResponse = null;
YouTube.Search.List search = youtube.search().list("id,snippet");
search.setKey("유튜브 API KEY");
search.setType("video");
search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
search.setQ("키워드 입력");
searchResponse = search.execute();
List<SearchResult> searchResultList = searchResponse.getItems();

 

 

(5) 전체 코드

package com.gokchu.saye.music.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.gokchu.saye.repository.dto.Music;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.ResourceId;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;

@Service
public class YoutubeServiceImpl implements YoutubeService {

	/** Global instance properties filename. */
	private static String PROPERTIES_FILENAME = "youtube.properties";

	/** Global instance of the HTTP transport. */
	private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

	/** Global instance of the JSON factory. */
	private static final JsonFactory JSON_FACTORY = new JacksonFactory();

	/**
	 * Global instance of the max number of videos we want returned (50 = upper
	 * limit per page).
	 */
	private static final long NUMBER_OF_VIDEOS_RETURNED = 1;

	/** Global instance of Youtube object to make all API requests. */
	private static YouTube youtube;

	/**
	 * Initializes YouTube object to search for videos on YouTube
	 * (Youtube.Search.List). The program then prints the names and thumbnails of
	 * each of the videos (only first 50 videos).
	 *
	 * @param args command line args.
	 * @throws IOException
	 */

	// youtube url 가져오기
	@Override
	public ArrayList<Music> selectUrlByTitle() {
		String musicurl = "";
		ArrayList<Music> result = new ArrayList<Music>();

			try {

				youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {
					public void initialize(HttpRequest request) 
                    throws IOException {
					}})
                    .setApplicationName("youtube-cmdline-search-sample")
                    .build();
				SearchListResponse searchResponse = null;
				YouTube.Search.List search = youtube.search().list("id,snippet");
				search.setKey("유튜브 API KEY");
				search.setType("video");
				search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
				search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
				search.setQ("키워드 입력");
				searchResponse = search.execute();
				System.out.println(temp.get(j).getmUrl());
				List<SearchResult> searchResultList = searchResponse.getItems();

				if (searchResultList != null) {
					SearchResult singleVideo = searchResultList.get(0);
					ResourceId rId = singleVideo.getId();
					musicurl = rId.getVideoId();
					temp.get(j).setmUrl("https://www.youtube.com/watch?v=" + musicurl);
					result.add(temp.get(j));
					System.out.println("\n-------------------------------------------------------------\n");
//					musicurl = prettyPrint(searchResultList.iterator(), queryTerm);

				}

			} catch (GoogleJsonResponseException e) {
				j--;
				System.err.println(
						"There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
				continue;
			} catch (IOException e) {
				System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
				break;
			} catch (Throwable t) {
				// Use a logger to log this exception
				// t.printStackTrace();
				break;
			}

		return result;
	}
}

 

위의 코드를 활용해서 유튜브 api에서 url을 뽑아 올수 있게 제작했다.

 

 

728x90
Comments