본문 바로가기
jsp

네이버 API 사용하기

by 신방동불주먹 2022. 12. 13.

 

 

https://developers.naver.com/main/

 

NAVER Developers

네이버 오픈 API들을 활용해 개발자들이 다양한 애플리케이션을 개발할 수 있도록 API 가이드와 SDK를 제공합니다. 제공중인 오픈 API에는 네이버 로그인, 검색, 단축URL, 캡차를 비롯 기계번역, 음

developers.naver.com

 

 

Client ID : EccB66AnnjcljM14yKyi

Client Secret : Kl94N8_pGX

 

 

 

 

 

<코드수정>

main 함수 코드 service에 복붙

      		  String clientId = "EccB66AnnjcljM14yKyi"; //애플리케이션 클라이언트 아이디
	        String clientSecret = "Kl94N8_pGX"; //애플리케이션 클라이언트 시크릿


	        int startNum = 0;
	        String text = null;
	        try {
	        	startNum = Integer.parseInt(request.getParameter("startNum")); //페이지 번호 받아옴
	        	String searchText = request.getParameter("keyword"); //검색어 받아오는 부분
	            text = URLEncoder.encode(searchText, "UTF-8"); //실제 검색하기 위한 키워드
	        } catch (UnsupportedEncodingException e) {
	            throw new RuntimeException("검색어 인코딩 실패",e);
	        }


	        String apiURL = "https://openapi.naver.com/v1/search/blog?query=" + text
	        		+ "&display=10&start=" + startNum ;//한번에 10개씩 보여줄거고, 첫번째 시작값은 startNum 기준으로 할거다 ->api 문서에 써있음   // JSON 결과
	        //String apiURL = "https://openapi.naver.com/v1/search/blog.xml?query="+ text; // XML 결과


	        Map<String, String> requestHeaders = new HashMap<>();
	        requestHeaders.put("X-Naver-Client-Id", clientId);
	        requestHeaders.put("X-Naver-Client-Secret", clientSecret);
	        String responseBody = get(apiURL,requestHeaders);

	        System.out.println(responseBody);
	        response.setContentType("text/html; charset=utf-8");
	        response.getWriter().write(responseBody); //브라우저에서 네이버에서 보내준 결과를 볼 수 있음
	}

 

발급받은 id, secret 으로 수정

	        String clientId = "EccB66AnnjcljM14yKyi"; //애플리케이션 클라이언트 아이디
	        String clientSecret = "Kl94N8_pGX"; //애플리케이션 클라이언트 시크릿

 

 

service 끝나는 부분 

 

    private static String get(String apiUrl, Map<String, String> requestHeaders){
        HttpURLConnection con = connect(apiUrl);
        try {
            con.setRequestMethod("GET");
            for(Map.Entry<String, String> header :requestHeaders.entrySet()) {
                con.setRequestProperty(header.getKey(), header.getValue());
            }


            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // 정상 호출
                return readBody(con.getInputStream());
            } else { // 오류 발생
                return readBody(con.getErrorStream());
            }
        } catch (IOException e) {
            throw new RuntimeException("API 요청과 응답 실패", e);
        } finally {
            con.disconnect();
        }
    }


    private static HttpURLConnection connect(String apiUrl){
        try {
            URL url = new URL(apiUrl);
            return (HttpURLConnection)url.openConnection();
        } catch (MalformedURLException e) {
            throw new RuntimeException("API URL이 잘못되었습니다. : " + apiUrl, e);
        } catch (IOException e) {
            throw new RuntimeException("연결이 실패했습니다. : " + apiUrl, e);
        }
    }


    private static String readBody(InputStream body){
        InputStreamReader streamReader = new InputStreamReader(body);


        try (BufferedReader lineReader = new BufferedReader(streamReader)) {
            StringBuilder responseBody = new StringBuilder();


            String line;
            while ((line = lineReader.readLine()) != null) {
                responseBody.append(line);
            }


            return responseBody.toString();
        } catch (IOException e) {
            throw new RuntimeException("API 응답을 읽는 데 실패했습니다.", e);
        }
    }

 

 

테스트

http://localhost:8081/NaverSearchAPI/NaverSearchAPI.do?keyword=%EA%B3%B5%EB%A3%A1&startNum=1

 

json 형태로 반환

 

"items":[ { "title":"고고다이노 우리동네공룡<\/b> 뮤지컬 나루아트센터 후기 주차팁", 
	"link":"https:\/\/blog.naver.com\/0129jk\/222945404160", 
	"description":"내돈내산 후기 고고다이노 우리동네공룡<\/b> 뮤지컬이 광진구 나루아트센터에서 공연하고 있어요. 오늘이... 고고다이노 우리동네공룡<\/b> 뮤지컬 @나루아트센터 공연 일정 ~2022년 12월 11일 일요일까지 공연 시간 화~금... ", 
	"bloggername":"루나네집", 
	"bloggerlink":"blog.naver.com\/0129jk", 
	"postdate":"20221204" 
	},

 

 

'jsp' 카테고리의 다른 글

공공데이터포털 api  (0) 2022.12.13
카카오 API 사용  (0) 2022.12.13
SMTP 활용 이메일 전송  (0) 2022.12.12
게시판_model2_2  (0) 2022.12.08
서블릿.do 에서 -> 액션.jsp  (0) 2022.12.07