web developer

[java] youtube Data API [1] : Search / json 구조의 응답 본문을 반환받기 본문

Language/Java

[java] youtube Data API [1] : Search / json 구조의 응답 본문을 반환받기

trueman 2023. 10. 25. 16:49
728x90
728x90

Search: list

API 요청에 지정된 쿼리 매개변수와 일치하는 검색결과 컬렉션을 반환합니다.

 

(1) HTTP 요청 

GET https://www.googleapis.com/youtube/v3/search

(2) 쿼리 매개변수

q : q 매개변수는 검색할 검색어를 지정합니다.

나머지 : https://developers.google.com/youtube/v3/docs/search/list?hl=ko

 

(3) 응답

요청에 성공할 경우 이 메소드는 다음과 같은 구조의 응답 본문을 반환합니다.

{
  "kind": "youtube#searchListResponse",
  "etag": etag,
  "nextPageToken": string,
  "prevPageToken": string,
  "regionCode": string,
  "pageInfo": {
    "totalResults": integer,
    "resultsPerPage": integer
  },
  "items": [
    search Resource
  ]
}

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

    StringBuffer response = null;
    String apiurl = "https://www.googleapis.com/youtube/v3/search";
    String apikey = "발급받은 API KEY";

    try {
        apiurl += "?key=" + apikey;
        apiurl += "&part=snippet&type=video&maxResults=3&videoEmbeddable=true";
        apiurl += "&q="+URLEncoder.encode(search,"UTF-8");

        URL url = new URL(apiurl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");

        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
        String inputLine;
        response = new StringBuffer();
        while((inputLine = br.readLine()) != null) {
            response.append(inputLine);
        }		    
        br.close();

    }catch(Exception e) {
        System.out.println("예외상황 발생");
        e.printStackTrace();
    }
    return response.toString();
}

반환된 응답 본문

 

* 키워드 : 당근마켓

{
  "kind": "youtube#searchListResponse",
  "etag": "i2CetR_2wrz5qspYf_KLxta_aPg",
  "nextPageToken": "CAMQAA",
  "regionCode": "KR",
  "pageInfo": {
    "totalResults": 1000000,
    "resultsPerPage": 3
  },
  "items": [
    {
      "kind": "youtube#searchResult",
      "etag": "Zmx8id8rRzQ61Rf49sJ2QGwPFR0",
      "id": {
        "kind": "youtube#video",
        "videoId": "dxnHKwMz5kQ"
      },
      "snippet": {
        "publishedAt": "2023-05-13T14:02:05Z",
        "channelId": "UC9ta639M37zzWKwo7kKc80A",
        "title": "정신 나갈 것 같은 당근마켓 빌런 모음ㅋㅋㅋ",
        "description": "이 영상 생방송 원본 다시보기   https://www.youtube.com/watch?v=b17FKCk0xQs 생방송은 화/토 제외 늦은 밤(10~12시 랜덤 알림 ...",
        "thumbnails": {
          "default": {
            "url": "https://i.ytimg.com/vi/dxnHKwMz5kQ/default.jpg",
            "width": 120,
            "height": 90
          },
          "medium": {
            "url": "https://i.ytimg.com/vi/dxnHKwMz5kQ/mqdefault.jpg",
            "width": 320,
            "height": 180
          },
          "high": {
            "url": "https://i.ytimg.com/vi/dxnHKwMz5kQ/hqdefault.jpg",
            "width": 480,
            "height": 360
          }
        },
        "channelTitle": "주둥이방송",
        "liveBroadcastContent": "none",
        "publishTime": "2023-05-13T14:02:05Z"
      }
    },
    {
      "kind": "youtube#searchResult",
      "etag": "Rkv3Itew5N_94CnyajfIOoMOah8",
      "id": {
        "kind": "youtube#video",
        "videoId": "2-sDtfYPt90"
      },
      "snippet": {
        "publishedAt": "2023-07-16T23:00:00Z",
        "channelId": "UC8tsBsQBuF7QybxgLmStihA",
        "title": "우리동네 모~든 알바, 당근알바 (bgm 당근알바 쏭)",
        "description": "올여름 낭만 알바 절찬리 모집 중!(~7.30) 최대 300만원 여행 지원금 받고 로마, 발리, 오사카, 여수로 낭만 알바 떠나세요!",
        "thumbnails": {
          "default": {
            "url": "https://i.ytimg.com/vi/2-sDtfYPt90/default.jpg",
            "width": 120,
            "height": 90
          },
          "medium": {
            "url": "https://i.ytimg.com/vi/2-sDtfYPt90/mqdefault.jpg",
            "width": 320,
            "height": 180
          },
          "high": {
            "url": "https://i.ytimg.com/vi/2-sDtfYPt90/hqdefault.jpg",
            "width": 480,
            "height": 360
          }
        },
        "channelTitle": "당근",
        "liveBroadcastContent": "none",
        "publishTime": "2023-07-16T23:00:00Z"
      }
    },
    {
      "kind": "youtube#searchResult",
      "etag": "CL8OqFfGalVBWaGFYXdP0tonguI",
      "id": {
        "kind": "youtube#video",
        "videoId": "3z7de4O0bFU"
      },
      "snippet": {
        "publishedAt": "2022-12-21T09:42:38Z",
        "channelId": "UCAoj0YC4IC_pgEZvqr0OAZw",
        "title": "당근마켓으로 총 1000만원 이상 번 7가지 꿀팁 대방출",
        "description": "N가지 무료 전자책 & 특강(수천만원 상당) : https://www.money-book.co.kr/40 * 곤팀장 블로그 : https://blog.naver.com/sungon531.",
        "thumbnails": {
          "default": {
            "url": "https://i.ytimg.com/vi/3z7de4O0bFU/default.jpg",
            "width": 120,
            "height": 90
          },
          "medium": {
            "url": "https://i.ytimg.com/vi/3z7de4O0bFU/mqdefault.jpg",
            "width": 320,
            "height": 180
          },
          "high": {
            "url": "https://i.ytimg.com/vi/3z7de4O0bFU/hqdefault.jpg",
            "width": 480,
            "height": 360
          }
        },
        "channelTitle": "돈버는 공략집, 곤팀장",
        "liveBroadcastContent": "none",
        "publishTime": "2022-12-21T09:42:38Z"
      }
    }
  ]
}

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

 

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

쿼리 매개변수 쿼리 매개변수 설명 q - 검색할 검색어를 지정합니다. - 또한 부울 부울 (-) 및 OR (|) 연산자를 사용하여 동영상을 제외하거나 여러 검색어 중 하나와 연결된 동영상을 찾을 수 있습

take-it-into-account.tistory.com


참조 : https://developers.google.com/api-client-library/java/google-api-java-client/download?hl=ko [ API 라이브러리 다운로드 ]

출처 : https://kunduz.tistory.com/entry/Youtube-API-%EC%9C%A0%ED%8A%9C%EB%B8%8C-1-Youtube-API-%ED%82%A4-%EB%B0%9C%EA%B8%89%ED%95%98%EA%B8%B0 [ youtube API 키 발급하기 ]

 

728x90
728x90