web developer

[java] youtube Data API [2] : Search / JSON data를 JSONObject로 변환하여 결과 확인하기 본문

Language/Java

[java] youtube Data API [2] : Search / JSON data를 JSONObject로 변환하여 결과 확인하기

trueman 2023. 10. 27. 23:23
728x90
728x90

쿼리 매개변수 

 

쿼리 매개변수 설명
q - 검색할 검색어를 지정합니다.
- 또한 부울 부울 (-) 및 OR (|) 연산자를 사용하여 동영상을 제외하거나 여러 검색어 중 하나와 연결된 동영상을 찾을 수 있습니다. 예를 들어 '보트' 또는 '세일링'과 일치하는 동영상을 검색하려면 q 매개변수 값을 boating|sailing로 설정합니다. 마찬가지로 '보트' 또는 '세일링'과 일치하지만 '낚시'와는 일치하지 않는 동영상을 검색하려면 q 매개변수 값을 boating|sailing -fishing로 설정합니다. 
- 파이프 문자는 API 요청에서 전송될 때 URL 이스케이프 처리되어야 합니다. 파이프 문자의 URL 이스케이프 값은 %7C입니다.
type - 특정 유형의 리소스만 검색하도록 검색어를 제한합니다. 
- 값은 쉼표로 구분된 리소스 유형 목록입니다. 기본값은 video,channel,playlist입니다.
maxResults - 받아올 데이터의 수량을 지정합니다. 데이터의 수령 할당량과 밀접한 연관이 있습니다.
publishedAfter - 지정 시간 이후에 업로드된 영상만 검색합니다. 
- 값은 RFC 3339 형식이 지정된 날짜-시간 값(1970-01-01T00:00:00Z)입니다.
publishedBefore - 지정 시간 이전에 업로드된 영상만 검색합니다. 
- 값은 RFC 3339 형식이 지정된 날짜-시간 값(1970-01-01T00:00:00Z)입니다.
videoEmbeddable - 웹페이지에 삽입할 수 있는 동영상으로만 검색을 제한할 수 있습니다.
- 이 매개변수의 값을 지정하는 경우 type 매개변수의 값도 video로 설정해야 합니다.

Java
@ResponseBody
@RequestMapping(value="/keywordSearch.do", method=RequestMethod.POST)
public String keywordSearch(@RequestParam("search") String search) throws IOException {

    ArrayList<String> youtubeList = new ArrayList<String>();
    StringBuffer response = null;
    String apiurl = "https://www.googleapis.com/youtube/v3/search";
    String apikey = "발급받은 API KEY";
    
    // 시작일
    String startDate = "2023-01-01"; 
    LocalDate startLocaldate = LocalDate.parse(startDate);
    String startFormatDate = startLocaldate.atStartOfDay().toInstant(ZoneOffset.UTC).toString(); // "2023-01-01T00:00:00Z";
	
    // 종료일
    String endDate = "2023-12-31";
    LocalDate endLocaldate = LocalDate.parse(endDate);
    String endFormatDate = endLocaldate.atStartOfDay().toInstant(ZoneOffset.UTC).toString(); // "2023-12-31T23:59:59Z";
	
    // 필드 
    String fields = "items(id,snippet(publishedAt,title,description,thumbnails))";
    try {
        apiurl += "?key=" + apikey;
        apiurl += "&part=snippet&type=video&maxResults=3&videoEmbeddable=true";
        apiurl += "&q="+URLEncoder.encode(search,"UTF-8"); // keyword
        apiurl += "&publishedAfter="+startFormatDate; // start date 
        apiurl += "&publishedBefore="+endFormatDate;  // end date
        apiurl += "&fields="+URLEncoder.encode(fields,"UTF-8");
        
        // url 연결
        URL url = new URL(apiurl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        
        // SSLHandshakeException 에러 발생으로 인한 우회 방법 : S
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType){
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };

        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        con.connect();
        // SSLHandshakeException 에러 발생으로 인한 우회 방법 : E
        
        // json data 생성
        String result ="";
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
        String inputLine;
        response = new StringBuffer();
        while((inputLine = br.readLine()) != null) {
            response.append(inputLine);
            System.out.println(inputLine);
        }		    
        br.close();    		

        //String에 담는다.
        result = response.toString();
        //JSONParser
        JSONParser jsonParser = new JSONParser();
        //JSON데이터를 넣어 JSON Object 로 만들어 준다.
        JSONObject jsonObject = (JSONObject) jsonParser.parse(result);
        //books의 배열을 추출
        JSONArray youtubeArray = (JSONArray) jsonObject.get("items");

        for (int i = 0; i < youtubeArray.size(); i++) {
            JSONObject data = (JSONObject) youtubeArray.get(i);

            // 유튜브 비디오 ID .getJSONObject("id");
            JSONObject id = (JSONObject) data.get("id");
            String videoId = id.get("videoId").toString();
            youtubeList.add(videoId);

            // 유튜브 제목
            JSONObject snippet = (JSONObject) data.get("snippet");
            String title = snippet.get("title").toString();
            youtubeList.add(title);
            
            // 유튜브 내용 
            String description = snippet.get("description").toString();
            youtubeList.add(description);

            // 유튜브 썸네일 이미지 디폴트
            JSONObject thumb = (JSONObject) snippet.get("thumbnails");
            JSONObject thumb_default = (JSONObject) thumb.get("default");
            String thumbUrl = thumb_default.get("url").toString();
            youtubeList.add(thumbUrl);

            // 유튜브 썸네일 이미지 가장 큰 크기
            JSONObject high = (JSONObject) thumb.get("high");
            String thumbUrl_high = high.get("url").toString();
            youtubeList.add(thumbUrl_high);
        }
        for(int j=0; j<youtubeList.size(); j++) {
            System.out.println(youtubeList.get(j));
        }
    }catch(Exception e) {
        System.out.println("예외상황 발생");
    }
    return null;
}

결과

 

* 키워드 : 당근마켓

videoId       : dxnHKwMz5kQ
title         : 정신 나갈 것 같은 당근마켓 빌런 모음ㅋㅋㅋ
description   : 이 영상 생방송 원본 다시보기   https://www.youtube.com/watch?v=b17FKCk0xQs 생방송은 화/토 제외 늦은 밤(10~12시 랜덤 알림 ...
thumbUrl      : https://i.ytimg.com/vi/dxnHKwMz5kQ/default.jpg
thumbUrl_high : https://i.ytimg.com/vi/dxnHKwMz5kQ/hqdefault.jpg

videoId       : 2-sDtfYPt90
title         : 우리동네 모~든 알바, 당근알바 (bgm 당근알바 쏭)
description   : 올여름 낭만 알바 절찬리 모집 중!(~7.30) 최대 300만원 여행 지원금 받고 로마, 발리, 오사카, 여수로 낭만 알바 떠나세요!
thumbUrl      : https://i.ytimg.com/vi/2-sDtfYPt90/default.jpg
thumbUrl_high : https://i.ytimg.com/vi/2-sDtfYPt90/hqdefault.jpg

videoId       : 3z7de4O0bFU
title         : 당근마켓으로 총 1000만원 이상 번 7가지 꿀팁 대방출
description   : N가지 무료 전자책 & 특강(수천만원 상당) : https://www.money-book.co.kr/40 * 곤팀장 블로그 : https://blog.naver.com/sungon531.
thumbUrl      : https://i.ytimg.com/vi/3z7de4O0bFU/default.jpg
thumbUrl_high : https://i.ytimg.com/vi/3z7de4O0bFU/hqdefault.jpg

https://take-it-into-account.tistory.com/286

 

[java] youtube Data API [3] : Search / 여러 개 channel의 검색결과 가져와서 db 입력하기

여러 개 channel에서 키워드 검색을 통한 검색결과를 가져오는 방법 (1) keywordSearchData를 호출시키면 youtube channel id 여러개를 youtubeDataAPI 메소드에 전달한다. (2) youtube Data API 할당량이 정해져 있기

take-it-into-account.tistory.com


참조 : https://lasdri.tistory.com/794 [유튜브 검색결과를 JSON으로 받아오기 ]

참조 : https://luvris2.tistory.com/285 [ 유튜브 검색결과를 받아올 때 받아올 데이터 설정 ]

참조 : https://kimcoder.tistory.com/333 [ URI 요청으로 JSON 데이터를 받았을 경우 처리하는 방법 ]

참조 :  https://postitforhooney.tistory.com/46 [ JSONParser ]
참조 : https://luvris2.tistory.com/285 [ Array for문 돌려서 데이터 가져오기 ]

참조 : https://ming9mon.tistory.com/137 [ org.json.simple.JSONObject cannot be cast to net.sf.json.JSONObject ]

참조 : https://deersoul6662.tistory.com/228 [org.json.simple.JSONObject cannot be cast to net.sf.json.JSONObject ]

 

23/11/07 추가 [ SSLHandshakeException 에러 발생으로 인한 우회 방법 ]

참조 : https://goddaehee.tistory.com/268 

참조 : https://365kim.tistory.com/93

참조 : https://dazbee.tistory.com/57

참조 : https://tmxhsk99.tistory.com/184

728x90
728x90