쩡스토리

공공데이터포털 OPEN API 사용법 (2) 본문

IT/기타

공공데이터포털 OPEN API 사용법 (2)

정Aa 2021. 3. 7. 00:10

 

저번 시간에 발급받은 OPEN API KEY 를 활용해보자!

 

 

(저번 시간과 다른 API를 발급 받았다,, 오늘은 "국토교통부_국내항공운항정보" 로 합니다!)

 

 

1. 먼저, 발급받은 API의 상세 화면을 보면 신청한 상세기능별로 요청변수, 출력결과, 샘플코드가 나와있다.

 

 

나는 항공운행정보목록 조회를 선택!

 

 

2. 하단에 언어별 샘플코드가 나와있다.

   원하는 언어 선택하여 샘플코드를 확인하자!

 

나는 JAVA 선택~!

 

JAVA 샘플코드

 

3. 샘플코드를 복사하여 원하는 클래스 파일에 붙여넣는다.

import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.io.BufferedReader;
import java.io.IOException;

public class ApiExplorer {
    public static void main(String[] args) throws IOException {
        StringBuilder urlBuilder = new StringBuilder("http://openapi.tago.go.kr/openapi/service/DmstcFlightNvgInfoService/getFlightOpratInfoList"); /*URL*/
        urlBuilder.append("?" + URLEncoder.encode("ServiceKey","UTF-8") + "=서비스키"); /*Service Key*/
        urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=" + URLEncoder.encode("10", "UTF-8")); /*한 페이지 결과 수*/
        urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=" + URLEncoder.encode("1", "UTF-8")); /*페이지 번호*/
        urlBuilder.append("&" + URLEncoder.encode("depAirportId","UTF-8") + "=" + URLEncoder.encode("NAARKJJ", "UTF-8")); /*출발공항ID*/
        urlBuilder.append("&" + URLEncoder.encode("arrAirportId","UTF-8") + "=" + URLEncoder.encode("NAARKPC", "UTF-8")); /*도착공항ID*/
        urlBuilder.append("&" + URLEncoder.encode("depPlandTime","UTF-8") + "=" + URLEncoder.encode("20201201", "UTF-8")); /*출발일*/
        urlBuilder.append("&" + URLEncoder.encode("airlineId","UTF-8") + "=" + URLEncoder.encode("AAR", "UTF-8")); /*항공사ID*/
        URL url = new URL(urlBuilder.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-type", "application/json");
        System.out.println("Response code: " + conn.getResponseCode());
        BufferedReader rd;
        if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        } else {
            rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        }
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();
        conn.disconnect();
        System.out.println(sb.toString());
    }
}

 

4. 한글 출력을 위하여 UTF-8를 추가한다.

if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
	rd = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
} else {
	rd = new BufferedReader(new InputStreamReader(conn.getErrorStream(),"UTF-8"));
}

 

 

5. 원하는 클래스명, 타입으로 변경한다. (MAP으로 변경했다.)

public static Map<String, Object> FlightOpratInfoApi() throws Exception{
		
	Map<String, Object> resultMap = new HashMap<>();

    try {
        StringBuilder urlBuilder = new StringBuilder("http://openapi.tago.go.kr/openapi/service/DmstcFlightNvgInfoService/getFlightOpratInfoList"); /*URL*/
        urlBuilder.append("?" + URLEncoder.encode("ServiceKey","UTF-8") + "발급받은 API 키를 넣어주세요"); /*Service Key*/
        urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=" + URLEncoder.encode("10", "UTF-8")); /*한 페이지 결과 수*/
        urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=" + URLEncoder.encode("1", "UTF-8")); /*페이지 번호*/
        urlBuilder.append("&" + URLEncoder.encode("depAirportId","UTF-8") + "=" + URLEncoder.encode("NAARKJJ", "UTF-8")); /*출발공항ID*/
        urlBuilder.append("&" + URLEncoder.encode("arrAirportId","UTF-8") + "=" + URLEncoder.encode("NAARKPC", "UTF-8")); /*도착공항ID*/
        urlBuilder.append("&" + URLEncoder.encode("depPlandTime","UTF-8") + "=" + URLEncoder.encode("20201201", "UTF-8")); /*출발일*/
        urlBuilder.append("&" + URLEncoder.encode("airlineId","UTF-8") + "=" + URLEncoder.encode("AAR", "UTF-8")); /*항공사ID*/
        URL url = new URL(urlBuilder.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-type", "application/json");
        System.out.println("Response code: " + conn.getResponseCode());
        BufferedReader rd;
    if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
    	rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    } else {
    	rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
    }
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
    	sb.append(line);
    }
    rd.close();
    conn.disconnect();

    org.json.JSONObject xmlJSONObj = XML.toJSONObject(sb.toString());
    String xmlJSONObjString = xmlJSONObj.toString();
    System.out.println("### xmlJSONObjString=>"+xmlJSONObjString);

    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, Object> map = new HashMap<>();
    map = objectMapper.readValue(xmlJSONObjString, new TypeReference <Map<String,Object>>(){});
    Map<String, Object> dataResponse = (Map<String, Object>) map.get("response");
    Map<String, Object> body = (Map<String, Object>) dataResponse.get("body");
    Map<String, Object> items = null;
    List<Map<String, Object>> itemList = null;

    items = (Map<String, Object>) body.get("items");
    itemList = (List<Map<String, Object>>) items.get("item");

    System.out.println("### map="+map);
    System.out.println("### dataResponse="+dataResponse);
    System.out.println("### body="+body);
    System.out.println("### items="+items);
    System.out.println("### itemList="+itemList);

    resultMap.put("Result", "0000");
    resultMap.put("numOfRows", body.get("numOfRows"));
    resultMap.put("pageNo", body.get("pageNo"));
    resultMap.put("totalCount", body.get("totalCount"));
    resultMap.put("data", itemList);

    } catch (Exception e){
        e.printStackTrace();
        resultMap.clear();
        resultMap.put("Result", "0001");
    }

    return resultMap;
}

 

그리고 서버를 돌리면 !

 

콘솔창 출력

콘솔창에 System.out.println으로 찍었던 것들이 나온다.

 

 

성공적.

 

 

반응형
Comments