spring 환경에서 공공데이터 활용하기

이한영·2021년 11월 4일
0

spring

목록 보기
4/5

공공데이터활용

어제는 카카오로그인을 하기위한 카카오api를 활용하기 위해서

json파서를 활용을 해보앗고 오늘은 공공데이터를 활용하면서

xml파일을 파싱하는법을 배운다 ! 드가자잇!

일단 xml파싱을 하기위해 라이브러리가 하나 필요하다 !

JDOM이라는 라이브러리이다!

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6</version>
</dependency>

pom.xml에 이쁘게 추가를 해주자 ! 항상 Dependencies카테고리에 제대로 추가가 되었는지 보고 넘어가즈앗!

이렇게 하고나서 신청했던 공공데이터에 보면인증키와 api문서가 있다 ! 문서를 보면 사용법과 인증키를 넣는 곳이 이쁘게 잘 나와있다!!

이렇게 하고 나서 vo객체를 하나 만들었다.

vo객체에 변수명은 내가가져오고싶은 공공데이터의 프로퍼티명과 같은 이름으로 했다 !

private String title, tel, addr1, addr2, firstimage, 
	firstimage2, createdtime, mapx, mapy;

이렇게 만들었다!!

이제 공데에서 필수로 보내달라한 값들을 전달해보즈아!

컨트롤러를 하나 만들자

@RequestMapping("/")
	public String index(Model m) throws Exception{
		
		StringBuffer sb = new StringBuffer("http://api.visitkorea.or.kr/openapi/service/rest/KorService/areaBasedList?");
		
		
		sb.append("ServiceKey={서비스키}");
		sb.append("&areaCode=35");
		sb.append("&MobileOS=ETC");
		sb.append("&MobileApp=AppTest");
		sb.append("&pageNo=1");
		sb.append("&numOfRows=10");
		
		URL url = new URL(sb.toString());
		
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

문서에보면 필수적으로 보내줘야하는 값들이 있다!

하라는대로 보내주자 !! 서비스키에는 내가 발급받은 키를 넣어주자!

이렇게보내주고 나서 응답을 받을 데이터의 형식!(마임타입)과

어떤 요청을 할것인지 담았으니 보내보자!!

conn.setRequestProperty("Content-Type","application/xml");
		
conn.connect();

JDOM활용하여 파싱하기

SAXBuilder builder = new SAXBuilder();
		
		Document document = builder.build(conn.getInputStream());
		
		Element root = document.getRootElement();
		//루트의 자식!이니까 child를 얻어야한다!
		Element body = root.getChild("body");
		//body안에 있는 items라는 엘리먼트를 얻어야한다.
		Element items = body.getChild("items");
		//items안에있는 자식들을 가져오자 ! 여러개니까 리스트여야겠지 ? 타입은 엘리먼트 !!
		List<Element> item_list = items.getChildren("item");

파싱한 데이터를 하나씩 문자열로 받기

DataVO[] ar = new DataVO[item_list.size()];
		
		int i = 0;
		for(Element item:item_list) {
			
			String title = item.getChildText("title");
			String createdtime = item.getChildText("createdtime");
			String addr1 = item.getChildText("addr1");
			String addr2 = item.getChildText("addr2");
			String firstimage = item.getChildText("firstimage");
			String firstimage2 = item.getChildText("firstimage2");
			String mapx = item.getChildText("mapx");
			String mapy = item.getChildText("mapy");
			String tel = item.getChildText("tel");
			
			DataVO vo = new DataVO(title, tel, addr1, addr2, firstimage, firstimage2, createdtime, mapx, mapy);
			
			ar[i++] = vo;

이렇게 받아온 데이터를 list라는 이름으로 세션에 저장하고

index페이지에 표현하자 !

m.addAttribute("list", ar);
return "index";

good~

profile
동작구 사망연산자

0개의 댓글