Tech Collection

[Api 활용] Open Api 의 자료를 json으로 가져오기 본문

Build/Note

[Api 활용] Open Api 의 자료를 json으로 가져오기

eee_269 2021. 1. 18. 12:42
728x90
반응형

먼저 어떤 공공 API를 쓸 것인지 확인합니다.

https://www.data.go.kr/index.do

 

공공데이터 포털

국가에서 보유하고 있는 다양한 데이터를『공공데이터의 제공 및 이용 활성화에 관한 법률(제11956호)』에 따라 개방하여 국민들이 보다 쉽고 용이하게 공유•활용할 수 있도록 공공데이터(Datase

www.data.go.kr

 

로그인 후 API를 선택하고 활용신청 클릭

 

 

 

활용신청 후 일반 인증키 에 나와있는 항목이 서비스키 입니다.

 

참고문서를 다운받아 실행 후

 

REST(URI)를 가지고 와서 활용할 예정입니다.

 


프로젝트로 와서 Controller를 하나 만들어 줍니다.

 

 

@RestController
@RequestMapping("/api")
public class ApiController {

    @GetMapping("/allow_info/basic")
    public String allowBasic() {
        StringBuffer result = new StringBuffer();
        try {
            StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/1471057/MdcinPrductPrmisnInfoService1/getMdcinPrductList"); /*URL*/
            urlBuilder.append("?" + URLEncoder.encode("ServiceKey", "UTF-8") + "=발급받은 서비스키"); /*Service Key*/
            urlBuilder.append("&" + URLEncoder.encode("pageNo", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8")); /*페이지 번호*/
            urlBuilder.append("&" + URLEncoder.encode("numOfRows", "UTF-8") + "=" + URLEncoder.encode("10", "UTF-8")); /*한 페이지 결과수*/
            urlBuilder.append("&type=json"); /*결과 json 포맷*/
            URL url = new URL(urlBuilder.toString());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            BufferedReader rd;
            if (conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
                rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            } else {
                rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            }
            String line;
            while ((line = rd.readLine()) != null) {
                result.append(line + "\n");
            }
            rd.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result + "";
    }
}

 

입력 후 실행하면 localhost:8080/api/allow_info/basic 의 경로에서 json 데이터가 출력됩니다.

 

 

728x90
반응형