Java/Spring Framework

[ Spring ] OpenAPI Spring 구현

Mungwang 2023. 8. 25. 11:52

💎 index.jsp

💎 Script

📢 ajax를 통한 비동기방식 Json 방식

- const itemArr = data.response.body.items :  Json형식으로 응답받은 데이터가 있는 경로를 itemArr에 대입

↓ console.log(data) 

 
 $(function(){
       $("#btn1").click(function(){
          //Json 형식으로 응답 받을 때
           $.ajax({
                url : "air",
                data : { location : $("#location").val()},
                success : function(data) {
                     console.log(data);
                     //console.log(data.response.body.items);
                   
                    const itemArr = data.response.body.items;
                   
                    let value = "";
                   
                    for(let item of itemArr){
                        console.log(item);
                        value += "<tr>"
                                    +"<td>"+ item.stationName +"</td>"
                                    +"<td>"+ item.dataTime +"</td>"
                                    +"<td>"+ item.khaiValue +"</td>"
                                    +"<td>"+ item.pm10Value +"</td>"
                                    +"<td>"+ item.so2Value +"</td>"
                                    +"<td>"+ item.coValue +"</td>"
                                    +"<td>"+ item.no2Value +"</td>"
                                    +"<td>"+ item.o3Value +"</td>"
                                +"</tr>"
                    }
                   
                    $("#result1 > tbody").html(value);
                       
                }, error : function() {
                    console.log("통신 실패");
                }
           })
 

📢 ajax를 통한 비동기방식 XML 방식

-  $( '요소명' ).find( 매개변수 ) : 기준이 되는 요소의 하위 요소들 중 특정 요소를 찾을때 사용

HTML, XML은 같은 MARKUP LANGUAGE 이기 때문에 사용 가능하다.

↓  console.log(result)

 
  // 응답 데이터를 xml 형식으로 받을 때
           $.ajax({
               url : "air",
               data : {location : $("#location").val()},
               success : function(result){
                   console.log(result);
                   
                   // xml형식의 응답데이터를 받았을 때
                   // 1. 넘겨받은 데이터를 $() 제이쿼리화 시킨후
                   //    응답데이터 안에 실제 데이터가 담겨 있는 요소 선택
                   const itemArr = $(result).find("item");
                   
                   // 2. 반복문을 통해 실제 데이터가 담긴 요소들에 접근해서 동적으로 요소 만들기
                   let value;
                   itemArr.each(function(index, item){
                       
                       // console.log(item);
                       // console.log($(item).find("stationName").text());
                       
                       value += "<tr>"
                            +"<td>"+ $(item).find("stationName").text() +"</td>"
                            +"<td>"+ $(item).find("dataTime").text() +"</td>"
                            +"<td>"+ $(item).find("khaiValue").text() +"</td>"
                            +"<td>"+ $(item).find("pm10Value").text() +"</td>"
                            +"<td>"+ $(item).find("so2Value").text() +"</td>"
                            +"<td>"+ $(item).find("coValue").text() +"</td>"
                            +"<td>"+ $(item).find("no2Value").text() +"</td>"
                            +"<td>"+ $(item).find("o3Value").text() +"</td>"
                        +"</tr>"
                       
                   })
                   
                   // 3. 동적으로 만들어낸 요소를 화면에 출력
                   $("#result1 > tbody").html(value);
               },
               
               error : function(){
                   console.log("통신 실패");
               }
               
           })
 

💎 Spring

📢 AirPollutionJavaAppRun

public class AirPollutionJavaAppRun {
	
	// 발급받은 인증키 변수처리
	public static final String SERVICEKEY = "공공데이터에서 받은 개인키";
	
	public static void main(String[] args)throws IOException { // UnsupportedEncodingException의 부모로 예외처리

			// OpenAPI 서버로 요청하고자 하는 url 작성
			String url = "http://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty";
			url += "?serviceKey="+ SERVICEKEY ; // 서비스키가 제대로 부여되지 않았을 경우 =>This XML file does not appear to have any style information associated with it. The document tree is shown below.
			url += "&sidoName=" + URLEncoder.encode("서울","UTF-8");
			url += "&returnType=json";
			
			// System.out.println(url);
			
			// ** HttpUrlConnection 객체를 활용해서 OpenAPI 요청 절차 **
			
			// 1. 요청할 주소를 전달해서 java.net.URL 객체 생성하기
			URL requestUrl = new URL(url);
			
 			// 2. 생성된 URL 객체를가지고 HttpUrlConnection 객체 얻어내기
			HttpURLConnection urlConn = (HttpURLConnection)requestUrl.openConnection();
			
			// 3. 요청 시 필요한 Header 설정하기
			urlConn.setRequestMethod("GET");

			// 4. 해당 OpenAPI 서버로 요청 보낸 후 입력 스트림을 통해 응답데이터 받기 * BufferedReader 한줄씩 읽기
			BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
			
			String responseText = "";
			String line;
			
			while((line = br.readLine()) !=null) { // 한줄씩 읽어올 데이터가 있는동안 반복
				// System.out.println(line);
				responseText += line;
				
			}
			
			// System.out.println(responseText); // ↓ JSON 값
			
			// JsonObject, JsonArray 이용해서 파싱할 수있음 (gson 라이브러리)
			
			// json 데이터를 원하는 데이터만 추출하여 VO에 담기
			// 응답데이터 text를 JsonObject화 시키는 작업 (파싱)
			JsonObject totalObj = JsonParser.parseString(responseText).getAsJsonObject();
			
			// System.out.println("total : " + totalObj);
			
			// response 속성 접근
			JsonObject responseObj = totalObj.getAsJsonObject("response");
			// System.out.println("response : " + responseObj);
			
			// body 속성 접근
			JsonObject bodyObj = responseObj.getAsJsonObject("body");
			// System.out.println("body : " + bodyObj);
			
			// totalCount 속성 접근
			int totalCount = bodyObj.get("totalCount").getAsInt();
			// System.out.println("totalCount : "+ totalCount);
			
			// items(JsonArray형태) 속성 접근
			JsonArray itemArr = bodyObj.getAsJsonArray("items");
			// System.out.println("itemArr : "+ itemArr);
			
			ArrayList<Air> list = new ArrayList<>();
			
			for(int i=0; i<itemArr.size(); i++) { //length 말고 size로해야함
				
				// items에 담겨있는 item객체 하나씩 추출
				JsonObject item = itemArr.get(i).getAsJsonObject();
				// System.out.println(item);
				
				Air air = new Air();
				air.setStationName(item.get("stationName").getAsString());
				air.setDataTime(item.get("dataTime").getAsString());
				air.setKhaiValue(item.get("khaiValue").getAsString());
				air.setPm10Value(item.get("pm10Value").getAsString());
				air.setSo2Value(item.get("so2Value").getAsString());
				air.setCoValue(item.get("coValue").getAsString());
				air.setNo2Value(item.get("no2Value").getAsString());
				air.setO3Value(item.get("o3Value").getAsString());
				
				list.add(air);
				
			}
			
			// System.out.println("list : " + list);
			
			// list에 담긴 VO객체확인
			
			for(Air air : list) {
				
				System.out.println(air);
			}
			
			// 5. 다 사용한 스트림 객체 반납하기
			br.close();
			urlConn.disconnect();
			
			
	}
}

📢 VO

📢 OpenAPIController

// Json형식으로 대기오염 OpenAPI 활용하기
	@ResponseBody
	//@RequestMapping(value="air", produces = "application/json; charset=UTF-8")
	public String airMethod(String location) throws IOException {

		// OpenAPI 서버로 요청하고자 하는 url 작성
		String url = "http://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty";
		url += "?serviceKey="+ SERVICEKEY ; // 서비스키 추가
		url += "&sidoName=" + URLEncoder.encode(location,"UTF-8"); // 지역명 추가(한글이 들어가면 인코딩 처리해야함)
		url += "&returnType=json"; // 리턴 타입
		url += "&numOfRows=20"; // 결과 개수

		// 1. 작성된 url 정보를 넣어 URL 객체 생성
		URL requestUrl = new URL(url);

		// 2. 생성된 URL 객체로 URLConnection 생성
		HttpURLConnection urlConn = (HttpURLConnection) requestUrl.openConnection();

		// 3. 요청 시 필요한 Header 설정
		urlConn.setRequestMethod("GET");

		// 4. 해당 OpenAPI 서버로 요청 후 입력스트림을 통해서 응답데이터 읽어오기
		BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

		String responseText = "";
		String line;

		while((line = br.readLine()) != null){
			responseText += line;
		}

		// 5. 다 사용한 스트링 반납 및 연결 해제
		br.close();
		urlConn.disconnect();

		System.out.println(responseText);
		return responseText;
	}

	// xml 형식으로 대기오염 OpenApi 활용하기
	@RequestMapping(value="air", produces = "text/xml; charset=UTF-8")
	@ResponseBody
	public String airPollution(String location) throws IOException {

		// OpenAPI 서버로 요청하고자 하는 url 작성
		String url = "http://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty";
		url +="?serviceKey=" + SERVICEKEY;
		url +="&sidoName=" + URLEncoder.encode(location,"UTF-8");
		url +="&returnType=xml";
		url +="&numOfRows=10"; // 결과 개수

		// 1. 작성된 url 정보를 넣어 URL 객체 생성
		URL requestUrl = new URL(url);

		// 2. 생성된 URL 객체로 URLConnection 생성
		HttpURLConnection urlConn = (HttpURLConnection) requestUrl.openConnection();

		// 3. 요청 시 필요한 Header 설정
		urlConn.setRequestMethod("GET");

		// 4. 해당 OpenAPI 서버로 요청 후 입력스트림을 통해서 응답데이터 읽어오기
		BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

		String responseText = "";
		String line;

		while((line = br.readLine()) != null){
			responseText += line;
		}

		// 5. 다 사용한 스트링 반납 및 연결 해제
		br.close();
		urlConn.disconnect();

		System.out.println(responseText);
		
		return responseText;

	}

💎 결과