반응형
//주유소 시도별 평균가격(현재)
String targetUrl = "http://www.opinet.co.kr/api/avgSidoPrice.do?out=xml&code=개인키";
String jsonData = "";
BufferedReader br = null;
StringBuffer sb = null;
URL url = new URL(targetUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.connect();
br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
sb = new StringBuffer();
while ((jsonData = br.readLine()) != null) {
sb.append(jsonData + "\n");
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(sb.toString())));
NodeList nodelist = document.getElementsByTagName("OIL");
System.out.println(nodelist.getLength());
for(int i = 0 ; i < nodelist.getLength() ; i++) {
Node node = nodelist.item(i); //첫번째 element 얻기
String SIDOCD = getNodeContent(node.getChildNodes(), "SIDOCD");
String SIDONM = getNodeContent(node.getChildNodes(), "SIDONM");
String PRODCD = getNodeContent(node.getChildNodes(), "PRODCD");
String PRICE = getNodeContent(node.getChildNodes(), "PRICE");
String DIFF = getNodeContent(node.getChildNodes(), "DIFF");
String TRADE_DT = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
Map<String, Object> row = new HashMap<String, Object>();
row.put("tradeDt", TRADE_DT);
row.put("prodCd", "PROD."+PRODCD);
row.put("sidoCd", "SIDO."+SIDOCD);
row.put("price", PRICE);
// 저장로직
// ...
}
반응형