ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 대한민국 지하철 데이터 수집 - 방법1
    Language/Java 2025. 6. 25. 11:46

     

    1. 서울 열린데이터광장 데이터 수집

    1.1. API 키 발급

    • 서울 열린데이터광장 사이트에 접속 후 회원가입
    • 이용안내 > Open API 소개
    • 일반 인증키 신청 및 조회

    이용안내 > Open API 소개 > 인증키 발급

     

    인증키 발급

     

     

    1.2. OpenAPI 정보 조회

    공공데이터 > 공공데이터 > OPENAPI > `지하철역 정보` 검색

    공공데이터 > 공공데이터 > OPENAPI > `지하철역 정보` 검색

     

    검색된 서울교통공사_노선별 지하철역 정보 API 주소를 기준으로 데이터를 가져올 수 있다.

    // 서울교통공사_노선별 지하철역 정보
    String service = "SearchSTNBySubwayLineInfo";
    String apiUrl = String.format("http://openapi.seoul.go.kr:8088/%s/json/SearchSTNBySubwayLineInfo/1/1000/", apiKey);

     

    검색된 서울시 역사마스터 정보 API 주소를 기준으로 데이터를 가져올 수 있다.

    // 서울시 역사마스터 정보
    String service = "subwayStationMaster";
    String apiUrl = String.format("http://openapi.seoul.go.kr:8088/%s/json/subwayStationMaster/1/1000/", apiKey);

    서울시 역사마스터 정보

     

    2. 공공데이터포털

    2.1.1. API 키 발급

    • 공공데이터포털 사이트에 접속 후 회원가입
    • 데이터찾기 > 데이터목록
    • `국가철도공단_부산_지하철_주소데이터` 활용신청

    `국가철도공단_부산_지하철_주소데이터` 활용신청

     

    필자는 아래와 같이 신청하였다.

     

     

    실행코드는 대충 라애와 같이 짜면 되지 않을까??
    파이썬으로 하고 싶지만 관리포인트가 늘어나니깐..ㅠ

    위/경도는 공공포탈에서 받아올수 있는거는 api 추가해서 받아오고 안되는건 naver, kakao 지도 api 사용해서 받아오는식으로 하면될듯하다.

    package net.neoflat.common.helper.service;
    
    import com.fasterxml.jackson.databind.JsonNode;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import net.neoflat.common.core.util.ConversionUtils;
    
    public class CollectorUtils {
    
      private final static String OPEN_DATA_SEOUL_API_KEY = "발급받은 API KEY";
      private final static String PUBLIC_DATA_PORTAL_API_KEY = "발급받은 API KEY";
    
      public static void collectSubway() {
        System.out.println("");
        System.out.println("####################################################");
        System.out.println("############# 서울 열린데이터광장 데이터 수집 STARTED");
        collectSeoulOpenData();
        System.out.println("############# 서울 열린데이터광장 데이터 수집 ENDED");
        System.out.println("############# 공공데이터포털 데이터 수집 STARTED");
        collectPublicDataPortal();
        System.out.println("############# 공공데이터포털 데이터 수집 ENDED");
        System.out.println("####################################################");
        System.out.println("");
      }
    
      /**
       * 서울열린데이터
       */
      public static void collectSeoulOpenData() {
        try {
          // 서울시 역사마스터 정보
          String service = "subwayStationMaster";
          String apiUrl = String.format("http://openapi.seoul.go.kr:8088/%s/json/subwayStationMaster/1/1000/", OPEN_DATA_SEOUL_API_KEY);
    
          // URL 연결
          URL url = new URL(apiUrl);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setRequestMethod("GET");
    
          // 응답 코드 확인
          int responseCode = conn.getResponseCode();
          if (responseCode == 200) { // HTTP OK
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
    
            while ((inputLine = in.readLine()) != null) {
              response.append(inputLine);
            }
            in.close();
    
            // 결과 출력
            System.out.println("API 응답 데이터:");
            System.out.println(response.toString());
    
            // JSON 파싱 (ConversionUtils의 objectToJsonNodeSafe 사용)
            JsonNode node = ConversionUtils.objectToJsonNodeSafe(response.toString());
            if (node == null) {
              System.out.println("JSON 파싱 실패 또는 응답이 비어있음");
              return;
            }
            JsonNode infoNode = node.get(service);
            if (infoNode != null && infoNode.get("RESULT") != null && "INFO-000".equals(infoNode.get("RESULT").get("CODE").asText())) {
              JsonNode rowNode = infoNode.get("row");
              int rowCount = (rowNode != null && rowNode.isArray()) ? rowNode.size() : 0;
              System.out.println("서울시 역사마스터 정보 row 배열 갯수: " + rowCount);
            }
    
          } else {
            System.out.println("API 호출 실패. 응답 코드: " + responseCode);
          }
    
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    
      public static void collectPublicDataPortal() {
    
        // TODO. 국가철도공단_부산_지하철_주소데이터 (주소)
        System.out.println("######### 국가철도공단_부산_지하철_주소데이터");
        collectPublicDataPortalCall("15041101/v1/uddi:209f5216-4ff3-420c-a737-d1eaf534e14f");
    
        // TODO. 가철도공단_대구_지하철_주소데이터 (주소)
        System.out.println("######### 국가철도공단_대구_지하철_주소데이터");
        collectPublicDataPortalCall("15041102/v1/uddi:046430cf-057e-4821-a00b-d8e98ed42b1e");
    
        // TODO. 광주교통공사_문화노선도 현황 (역번호/주소/위/경도)
        System.out.println("######### 광주교통공사_문화노선도");
        collectPublicDataPortalCall("15109340/v1/uddi:5a909036-a60e-4a51-b9f6-e0e8aab660a1");
    
        // TODO. 대전교통공사 (역번호/주소)
        System.out.println("######### 대전교통공사_역사 출구 현황");
        collectPublicDataPortalCall("15043917/v1/uddi:685c837e-496b-43a0-bda6-dbe8a44278d0");
    
        System.out.println("######### 대전교통공사_역명 및 주소");
        collectPublicDataPortalDaejeonLocation();
      }
    
      public static void collectPublicDataPortalCall(String service) {
    
        try {
          String apiUrl = String.format("https://api.odcloud.kr/api/%s?page=1&perPage=1000&returnType=json&serviceKey=%s", service, PUBLIC_DATA_PORTAL_API_KEY);
    
          // URL 연결
          URL url = new URL(apiUrl);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setRequestMethod("GET");
    
          // 응답 코드 확인
          int responseCode = conn.getResponseCode();
          if (responseCode == 200) { // HTTP OK
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
    
            while ((inputLine = in.readLine()) != null) {
              response.append(inputLine);
            }
            in.close();
    
            // 결과 출력
            System.out.println("API 응답 데이터:");
            System.out.println(response.toString());
    
            // JSON 파싱 (ConversionUtils의 objectToJsonNodeSafe 사용)
            JsonNode node = ConversionUtils.objectToJsonNodeSafe(response.toString());
            if (node == null) {
              System.out.println("JSON 파싱 실패 또는 응답이 비어있음");
              return;
            }
            if (node.get("currentCount") != null) {
              JsonNode rowNode = node.get("data");
              int rowCount = (rowNode != null && rowNode.isArray()) ? rowNode.size() : 0;
              System.out.println("row 배열 갯수: " + rowCount);
            }
    
          } else {
            System.out.println("API 호출 실패. 응답 코드: " + responseCode);
          }
    
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    
      public static void collectPublicDataPortalDaejeonLocation() {
    
        try {
          String apiUrl = String.format("http://www.djtc.kr/OpenAPI/service/StationNameSVC/getStationName03?serviceKey=%s&stationNo=%s", PUBLIC_DATA_PORTAL_API_KEY, "117");
    
          // URL 연결
          URL url = new URL(apiUrl);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setRequestMethod("GET");
    
          // 응답 코드 확인
          int responseCode = conn.getResponseCode();
          if (responseCode == 200) { // HTTP OK
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
    
            while ((inputLine = in.readLine()) != null) {
              response.append(inputLine);
            }
            in.close();
    
            // 결과 출력
            System.out.println("API 응답 데이터:");
            System.out.println(response.toString());
    
            // JSON 파싱 (ConversionUtils의 objectToJsonNodeSafe 사용)
            JsonNode node = ConversionUtils.objectToJsonNodeSafe(response.toString());
            if (node == null) {
              System.out.println("JSON 파싱 실패 또는 응답이 비어있음");
              return;
            }
            if (node.get("currentCount") != null) {
              JsonNode rowNode = node.get("data");
              int rowCount = (rowNode != null && rowNode.isArray()) ? rowNode.size() : 0;
              System.out.println("row 배열 갯수: " + rowCount);
            }
    
          } else {
            System.out.println("API 호출 실패. 응답 코드: " + responseCode);
          }
    
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

     

    'Language > Java' 카테고리의 다른 글

    전국 동/리/시군구 데이터 수집  (0) 2025.06.25
    대한민국 지하철 데이터 수집 - 방법2  (0) 2025.06.25
    Spring Boot의 주요 이벤트 정리  (1) 2024.12.27
    logback 로그 설정  (0) 2024.10.29
    p6spy 로그 설정 방법  (1) 2024.09.27

    댓글

Designed by Tistory.