관리 메뉴

LIFE & IT

공공API data 활용(1) 본문

프로그래밍/JAVA

공공API data 활용(1)

프린이! 2021. 1. 28. 17:20

공공API XML data Parsing 해서 Database 에 담기

- httpconnection 활용

- DOM xml 활용

 

▷ 환경  

java, tibero 5 SP1

 

▷ Main

- /main/apiAir.java

package main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import DAO.airDAO;
import VO.airVO;

public class apiAir {

	public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException, SQLException {

		
		String key = "k9XI8kJQZE1zhYg1LK5b1hqVIgOCAIGnRWxTEOcGXZqno6MLehEZHlPkbQYYd31fpnYnX96OmxlOBfDJvEmIzw%3D%3D";
		
		String airurl = "http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getUnityAirEnvrnIdexSnstiveAboveMsrstnList?"
				+ "pageNo=1&numOfRows=10"
				+ "&ServiceKey="+key;

		String parsingUrl = ""; // Parsiong 할 URL
		
		//* URL 객체 생성후 URL을 호출하기 위한 코드 작성  
		// setRequestMethod : 응답 방식 - GET , setRequestProperty : 응답 헤더 - application/json 방식
		URL url = new URL(airurl);
		
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setRequestMethod("GET");
		conn.setRequestProperty("Content-type", "application/json");
		
		//응답 코드 : conn.getResponseCode()
		System.out.println("Response Code : "+ conn.getResponseCode());
		
		
		//* 응답 코드 성공 여부에 따라 분기 설정
		// URL 로 응답 받은 데이터 값은 inputstream 으로 꺼낼 수 있다.
		
		BufferedReader rd; // InputStreamReader 값을 담을 Reader버퍼함수
		
		if(conn.getResponseCode() >= 200 && conn.getResponseCode() <=300 ) {
			rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		}else {
			rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
		}
		
		
		// 받은 데이터를  Builder 에 담아 둔다.
		
		//StringBuilder sb = new StringBuilder();  // Builder 와 Buffer 차이 알아보기!
		StringBuffer sb = new StringBuffer();
		String line; 
		
		while ((line = rd.readLine()) != null) 
		{ 
			sb.append(line); 
			System.out.println(sb.append(line));	
		} 
	
		rd.close(); // ReaderBufferd 닫기
		
		conn.disconnect(); //HttpURLConnection 닫기
		
		
		//* XML 을 DATA로 옴기기 위한 코드
		
		//페이지에 접근해줄 Document객체 생성 
		//doc객체를 통해 파싱할 url의 요소를 읽어들인다. 
		//doc.getDocumentElement().getNodeName()을 출력하면 위 xml의 최상위 태그를 가져온다.

		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
		
		parsingUrl = url.toString();
		Document doc = dBuilder.parse(parsingUrl);

		
		//root tag 
		
		// Tree 구조 node 로 변환
		doc.getDocumentElement().normalize();
		
		// root tag 값 확인
		System.out.println("Root element : " + doc.getDocumentElement().getNodeName());
		
		// 파싱할 데이터 tag 의 리스트 수
		NodeList nList = doc.getElementsByTagName("item"); // <item> 태그요소
		System.out.println("파싱할 리스트 수 : " +  nList.getLength());
		
		airDAO airDao = new airDAO();
		
		for(int i = 0; i < nList.getLength(); i++) {
			Node nNode = nList.item(i); // <item> i 의 값을 nNode 에 넣는다.
			
			//Element node type 비교
			if(nNode.getNodeType() == Node.ELEMENT_NODE) {
				Element eElement = (Element) nNode;
				
				airVO airVo = new airVO();		
				
				System.out.println("========================");
				System.out.println(getTagValue("stationName",eElement));
				System.out.println(getTagValue("addr",eElement));
				
				airVo.setStationName(getTagValue("stationName",eElement));
				airVo.setAddr(getTagValue("addr",eElement));
				
				airDao.insertAir(airVo.getStationName(), airVo.getAddr());
				
			}
		}
	}
	
	//*tag 값의 정보를 가져오는 메소드
	private static String getTagValue(String tag, Element eElement) {
		
		NodeList nList = eElement.getElementsByTagName(tag).item(0).getChildNodes();
		Node nValue = (Node)nList.item(0);
		
		if(nValue == null) {
			return null;
		}
		return nValue.getNodeValue();
		
	}

}

 

 

▷ DAO

- /DAO/airDAO.java

package DAO;

import java.sql.*;

public class airDAO {
	
	private String tibero_url = "jdbc:tibero:thin:@localhost:8629:tibero";
	private String usr_id = "apitest";
	private String usr_pw = "apitest";
	
	private String className = "com.tmax.tibero.jdbc.TbDriver";

	Connection conn = null;


	PreparedStatement pstmt;
	ResultSet rstmt;
			

	private void connection() throws SQLException {
		
		try {
			Class.forName(className);
			conn = DriverManager.getConnection(tibero_url,usr_id,usr_pw);
		} catch (ClassNotFoundException e) {
			
			e.printStackTrace();
		}
	}
	
	public void insertAir(String stationName, String addr) throws SQLException {
		
		connection();
	
		String sql = "insert into APIAIR VALUES ( ? , ? )";
		
		pstmt = conn.prepareStatement(sql);
		
		pstmt.setString(1,stationName);
		pstmt.setString(2,addr);
		
		pstmt.executeUpdate(sql);
		
		pstmt.close();
		conn.close();
		
	}

}

 

 

▷ VO

- /VO/airVO.java

package VO;

public class airVO {
	
	private String stationName ;
	private String addr;
	
	
	public String getStationName() {
		return stationName;
	}
	public void setStationName(String stationName) {
		this.stationName = stationName;
	}
	public String getAddr() {
		return addr;
	}
	public void setAddr(String addr) {
		this.addr = addr;
	}
	

}

'프로그래밍 > JAVA' 카테고리의 다른 글

JAVA JVM 메모리 구조  (0) 2020.01.15
자바 쓰레드 기초(Java Thread Basic)  (0) 2020.01.03
자바 메모리 관리 - 스택 & 힙  (0) 2020.01.03
Swing Table 관련 Issues  (0) 2019.08.31