SpringBoot/개인프로젝트

트위치 API 스트림 정보 가져오기

2023. 5. 1. 12:11

https://dev.twitch.tv/docs/api/reference/#get-streams

 

Reference

Twitch Developer tools and services to integrate Twitch into your development or create interactive experience on twitch.tv.

dev.twitch.tv

 

curl -X GET 'https://api.twitch.tv/helix/streams' \
-H 'Authorization: Bearer 2gbdx6oar67tqtcmt49t3wpcgycthx' \
-H 'Client-Id: wbmytr93xzw8zbg0p1izqyzzc5mbiz'

요청 예시를 보면 헤더에 액세스토큰과 클라이언트 id를 담아 GET 방식으로 요청한다.

그리고 쿼리 파라미터를 포함하여 정보를 요청할 수 있다.

나는 한국 스트리머의 스트림 정보를 가져오고 싶어서 language를 쿼리 파라미터로 보냈다. 한국어는 ko이다.

 

public List<StreamInfoData> getStreamInfo(String language) {
    // 토큰이 유효하지 않다면 재발급
    String token = getAccessToken();
    if (!isAccessTokenValid(token)) {
        token = reGetAccessToken();
    }

    // 정보 요청
    HttpHeaders headers = new HttpHeaders();
    headers.setBearerAuth(token);
    headers.set("Client-Id", clientId);
    headers.setBearerAuth(token);
    HttpEntity<?> httpEntity = new HttpEntity<>(headers);
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://api.twitch.tv/helix/streams")
            .queryParam("language", language);
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<LinkedHashMap> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, LinkedHashMap.class);
    LinkedHashMap data = response.getBody();
    StreamInfo streamInfo = new StreamInfo(data);
    List<StreamInfoData> infoData = streamInfoToStreamInfoData(streamInfo);
    return infoData;
}

public List<StreamInfoData> streamInfoToStreamInfoData(StreamInfo streamInfo) {
    List<StreamInfoData> list = new ArrayList<>();
    int size = streamInfo.getData().size();
    for (int i = 0; i < size; i++) {
        ArrayList arrayList = streamInfo.getData();
        LinkedHashMap map = (LinkedHashMap) arrayList.get(i);
        StreamInfoData infoData = new StreamInfoData(map);
        list.add(infoData);
    }
    return list;
}

응답은 아래와 같은 형식으로 들어온다.

 

getBody()를 통해 data와  pagination을 가져올 수 있다.

 

받아온 정보를 담을 Dto를 만들어준다.

import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.LinkedHashMap;

@Getter
@RequiredArgsConstructor
public class StreamInfo {

    private final ArrayList data;
    private final Object pagination;

    public StreamInfo(LinkedHashMap map) {
        this.data = (ArrayList) map.get("data");
        this.pagination = map.get("pagination");
    }
}

 

그리고 스트리머의 스트림 정보를 담을 Dto를 만든다.

import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.LinkedHashMap;

@Getter
@RequiredArgsConstructor
public class StreamInfoData {

    private final String id;
    private final String user_id;
    private final String user_login;
    private final String user_name;
    private final String game_id;
    private final String game_name;
    private final String type;
    private final String title;
    private final ArrayList tags;
    private final Integer viewer_count;
    private final String started_at;
    private final String language;
    private final String thumbnail_url;
    private final boolean is_mature;

    public StreamInfoData(LinkedHashMap map) {
        this.id = (String) map.get("id");
        this.user_id = (String) map.get("user_id");
        this.user_login = (String) map.get("user_login");
        this.user_name = (String) map.get("user_name");
        this.game_id = (String) map.get("game_id");
        this.game_name = (String) map.get("game_name");
        this.type = (String) map.get("type");
        this.title = (String) map.get("title");
        this.tags = (ArrayList) map.get("tags");
        this.viewer_count = (Integer) map.get("viewer_count");
        this.started_at = (String) map.get("started_at");
        this.language = (String) map.get("language");
        this.thumbnail_url = (String) map.get("thumbnail_url");
        this.is_mature = (boolean) map.get("is_mature");
    }
}

 

Controller

@GetMapping("/")
public String index(Model model, @LoginUser SessionUser user) {

    if (user != null) {
        model.addAttribute("userName", user.getName());
    }
    model.addAttribute("streamInfoData", twitchService.getStreamInfo("ko"));
    return "index";
}

 

index.html

<div class="album py-5 bg-body-tertiary">
    <div class="container">
        <h2>현재 방송 중인 스트리머</h2>
        <br>
        <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
            <div class="col" th:each="list : ${streamInfoData}">
                <a th:href="@{/search/{streamer}(streamer=${list.getUser_login()})}" style="text-decoration: none; color: inherit">
                    <div class="card shadow-sm">
                        <img th:src="@{https://static-cdn.jtvnw.net/previews-ttv/live_user_{user_login}-{width}x{height}.jpg (user_login=${list.getUser_login()}, width=440, height=248)}">
                        <p th:text="${list.getUser_name()}">
                    </div>
                </a>
            </div>
        </div>
    </div>
</div>

이렇게 하면 스트림 정보를 받아올 수 있다.

 

'SpringBoot > 개인프로젝트' 카테고리의 다른 글

Summernote 적용  (0) 2023.05.01
트위치 OAuth 로그인  (0) 2023.05.01
트위치 API를 이용해 정보 가져오기  (0) 2023.05.01
트위치 API  (0) 2023.05.01
프로젝트 생성  (0) 2023.05.01
'SpringBoot/개인프로젝트' 카테고리의 다른 글
  • Summernote 적용
  • 트위치 OAuth 로그인
  • 트위치 API를 이용해 정보 가져오기
  • 트위치 API
ewok
ewok
기록장ewok 님의 블로그입니다.
ewok
기록장
ewok
전체
오늘
어제
  • 분류 전체보기
    • 웹개발 교육
      • HTML
      • CSS
      • JavaScript
      • Database
      • Java
      • jQuery
      • Ajax
      • Bootstrap
      • jsp
      • Spring
      • MyBatis
      • 프로젝트
    • JAVA
    • SpringBoot
      • 기초
      • AWS
      • 개인프로젝트
    • Spring Security
    • JPA
    • 테스트코드
    • Error
    • CS
      • 컴퓨터 구조
      • 이산수학
    • 알고리즘
      • 정리
      • Java
    • SQL
    • 자격증
      • SQLD
      • 정보처리기사
    • Git

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 생성자
  • base
  • 노랭이
  • sqld 자격증
  • SQLD
  • merge commit
  • sqld 합격
  • GIT
  • branch
  • 브랜치
  • org.springframework.beans.factory.UnsatisfiedDependencyException
  • org.hibernate.tool.schema.spi.CommandAcceptanceException
  • 버전 관리
  • this
  • git bash

최근 댓글

최근 글

hELLO · Designed By 정상우.
ewok
트위치 API 스트림 정보 가져오기
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.