[TOY 1] OP.GG 클론 코딩 - ①

GARY·2022년 4월 7일
0

toy1

목록 보기
2/2

OP.GG 사이트 클론 코딩 하기

발급 받은 라이엇 API 키를 사용해서 API를 호출하자!
-- API 호출에는 Apache에서 제공하는 HttpClient를 사용, 사용언어는 JAVA
-- 사용언어는 JAVA다.

1. Riot API 확인하기

  1. SUMMONER-V4 문서를 확인
    -- 소환사 정보를 받는 API는 총 5개가 존재한다. 이중 summonerName(소환사명)을 사용하여 값을 받아보자.

  2. 사용할 API를 클릭하고 하단에 테스트 툴을 사용해보자

  3. 응답코드가 200이라면 성공!

2. VSCode로 API 호출하는 코드 작성

  1. build.gradle - dependencies에 라이브러리를 추가해준다.
  • json-simple은 다운로드 받아 폴더에도 넣어줘야 한다.
// http client
implementation 'org.apache.httpcomponents:httpclient'
//json
implementation group: 'org.json', name: 'json', version: '20090211'
implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
  1. API 키 숨기기위해 resources > application.opgg.properties 생성 후 값 설정
#롤 api 키
RIOT_API_KEY=발급받은 키값
  1. gitignore에 등록

  2. API 문서에서 확인한 REQUEST URL과 REQUEST HEADERS를 참고해서 코드 작성

  • api 호출
package com.gnar.cloneprojectopgg;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

@RestController
@RequestMapping(value = "/lol")
public class OpggApiController {
    GRUtils grUtils = new GRUtils();

    @Value("${RIOT_API_KEY}")
    private String riotApiKey;
    
    private String riotUrl = "https://kr.api.riotgames.com";

    @GetMapping(path = "/findUserInfo/{searchName}")
    public JSONObject findUserInfo(@PathVariable(name = "searchName") String summonerName) {
        //소환사 명 인코딩
        summonerName = grUtils.URLEncode(summonerName);
        String requestUrl = riotUrl + "/lol/summoner/v4/summoners/by-name/" + summonerName;
        System.out.println("requestUrl 확인 : " + requestUrl);
        JSONObject jsonUserInfo = new JSONObject();
        try {
            jsonUserInfo = getApiJson(requestUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jsonUserInfo;
    }

    public JSONObject getApiJson(String requestURL) throws Exception{
        JSONObject jsonObj = new JSONObject();
        JSONParser jParser = new JSONParser();

        //get 메서드와 URL 설정
        HttpGet httpGet = new HttpGet(requestURL);

        //header 설정
        httpGet.addHeader("User-Agent", "Mozilla/5.0");
        httpGet.addHeader("Accept-Language", "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7");
        httpGet.addHeader("Accept-Charset", "application/x-www-form-urlencoded; charset=UTF-8");
        httpGet.addHeader("Origin", "https://developer.riotgames.com");
        httpGet.addHeader("X-Riot-Token", riotApiKey);

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = httpClient.execute(httpGet);

        if (response.getStatusLine().getStatusCode() == 200) {
            ResponseHandler<String> handler = new BasicResponseHandler();
            String body = handler.handleResponse(response);
            System.out.println("body : " + body);

            jsonObj = (JSONObject) jParser.parse(body);
            System.out.println("jParser : " + jParser);
        }else{
            System.out.println("response is error : " + response.getStatusLine().getStatusCode());
        }

        return jsonObj;
    }

}
  • URL 인코딩
package com.gnar.cloneprojectopgg;

import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * GRUtils
 */
public class GRUtils {
    //URL Encoding
    public String URLEncode(String url) {
        String enUrl = "";
        try {
            enUrl = URLEncoder.encode(url, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return enUrl;
    }
    

    //URL Ddcoding
    public String URLDecode(String url) {
        String deUrl = "";
        try {
            deUrl = URLDecoder.decode(url, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return deUrl;
    }
}
  1. 프로젝트를 실행하고 http://localhost:8080/clone-project-opgg/lol/findUserInfo/초코잠보 접속

json 형식으로 값을 잘 받아온다~ :)

profile
개발하는 개린이 개리

0개의 댓글