일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 회귀
- Spotify Api
- SWEA
- modern c++
- c
- linux
- CS
- 스포티파이
- 회원가입
- spring boot
- regression
- Computer Science
- 파이썬
- programmers
- SECS-II
- java
- 자바
- spotify
- C++
- Gem
- 프로그래머스
- Spring
- SW Expert Academy
- SECS
- MYSQL
- 백준
- python
- Spring JPA
- Baekjoon
- SECS/GEM
Archives
- Today
- Total
비버놀로지
[Youtube API 유튜브] 3. Spring boot 에서 Youtube API (Java) 본문
728x90
developers.google.com/youtube/v3/code_samples?hl=ko
위의 링크를 참고해서 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
'OPEN API 활용' 카테고리의 다른 글
[Youtube API 유튜브] 2. Youtube API 검색(Python) (0) | 2021.04.16 |
---|---|
[Youtube API 유튜브] 1. Youtube API 키 발급하기 (0) | 2021.04.16 |
[Spotify 스포티파이] 11. Spring Boot 추천서비스 (0) | 2021.03.25 |
[Spotify 스포티파이] 10. Spring Boot 제목ID로 검색 (0) | 2021.03.25 |
[Spotify 스포티파이] 9. Spring Boot Items 검색 (0) | 2021.03.25 |
Comments