Coding/JAVASCRIPT

[AJAX] 기상청 데이터 Parsing

Soocong 2022. 4. 4. 10:04

다운로드해서 라이브러리 추가하기

 

http://commons.apache.org/

 

Apache Commons – Apache Commons

Welcome to Apache Commons Apache Commons is an Apache project focused on all aspects of reusable Java components. The Apache Commons project is composed of three parts: The Commons Proper - A repository of reusable Java components. The Commons Sandbox - A

commons.apache.org

Apache Commons – Apache Commons

Codec, logging, proxy, httpclient를 들어가 Release에 들어가서 binary에서 zip파일로 다운받아줍니다.

1) Codec 다운

2) Proxy 다운

3) Logging 다운

4) httpcomponents 다운

http://archive.apache.org/dist/httpcomponents/

 

Index of /dist/httpcomponents

 

archive.apache.org

Index of /dist/httpcomponents

 

다운로드받은 파일을 압축을 풀어 .jar파일을 WEB-INF/lib 에 넣어줍니다.

.jav

 


기상청 데이터 파싱하기

 

 

http://www.kma.go.kr/search/kmaSearch.jsp

 

통합검색 > 기상청

단어의 철자가 정확한지 확인해 주세요 검색어의 단어 수를 줄이거나, 다른 검색어로 검색해 주세요. 보다 일반적인 검색어로 검색해 보세요.

www.kma.go.kr

https://www.weather.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=109

 

 

 

commandURL.properties

/proxy/parsing.do = com.java.parsing.command.ParsingXMLCommand
/proxy/pXML.do = com.java.parsing.command.ProxyCommand

 

pXML.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>

<c:set var="root" value="${pageContext.request.contextPath}" />
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${root}/XHR/xhr.js"></script>
<script type="text/javascript">
	function toServer(root){
		//var url = "https://www.weather.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=109";
		var url = root+ "/proxy/pXML.do";
		sendRequest("GET", url, null, fromServer);
	}
	
	function fromServer(){
		//alert(xhr.readyState + "," + xhr.status); //4,200
		if(xhr.readyState==4 && xhr.status==200){
			processXML();
		}
	}
	
	function processXML(){
		var xmlDoc = xhr.responseXML;
		console.log(xmlDoc);
		
		var location = xmlDoc.getElementsByTagName("location");
		//alert(location.length); //35
		
		var titleWf = xmlDoc.getElementsByTagName("wf");
		document.getElementById("titleWf").innerHTML = titleWf[0].childNodes[0].nodeValue; //childNodes[0]대신에 firstChild도 가능
		
		var city = location[1].getElementsByTagName("city");
		document.getElementById("city").innerText = city[0].firstChild.nodeValue;
		
		var data = location[1].getElementsByTagName("data");
		var wf = data[1].getElementsByTagName("wf");
		document.getElementById("wf").innerText = wf[0].firstChild.nodeValue;
	}
</script>
</head>
<body>
	<input type="button" value="오늘의 날씨" onclick="toServer('${root}')"/>
	<div>
		<span id="titleWf" style="color:red"></span><br /><br />
		<span id="city" style="color:blue"></span><br /><br />
		<span id="wf"></span><br /><br />
	</div>
</body>
</html>

 

ParsionXMLCommand.java

package com.java.parsing.command;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.java.command.Command;

public class ParsingXMLCommand implements Command {

    @Override
    public String proRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
	// TODO Auto-generated method stub

	return "/WEB-INF/views/ajax/proxy/pXML.jsp";
    }
}

 

ProxyCommand.java

package com.java.parsing.command;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

import com.java.command.Command;

public class ProxyCommand implements Command {

    @Override
    public String proRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
	// 프록시서버: 시스템에 방화벽을 가지고 있는 경우, 접근을 할 수 없다. 외부와 통신을 위해 만들어 놓은 서버
	// 	    방화벽 안쪽에 있는 서버들의 외부 연결은 프록시 서버를 통해 이루어진다. 
	
	String url = "https://www.weather.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=109";
	GetMethod method = new GetMethod(url);
	
	HttpClient client = new HttpClient();
	int statusCode = client.executeMethod(method);
	//logger.info(logMsg + statusCode);
	
	
	if(statusCode==HttpStatus.SC_OK) {
	    String result = method.getResponseBodyAsString();
	    //logger.info(logMsg + result);
	    
	    response.setContentType("application/xml;charset=utf-8"); // application/text, application/json
	    PrintWriter out = response.getWriter();
	    out.print(result);
	}
	return null;
    }
}