본문 바로가기
Spring

Server to Server의 연결 - Naver API 사용

by step 1 2021. 6. 26.
반응형

사용할 open api

https://developers.naver.com/docs/serviceapi/search/local/local.md#%EC%A7%80%EC%97%AD

 

지역 - Search API

지역 NAVER Developers - 검색 API 지역 검색 개발가이드 검색 > 지역 네이버 지역 서비스에 등록된 각 지역별 업체 및 상호 검색 결과를 출력해주는 REST API입니다. 비로그인 오픈 API이므로 GET으로 호출

developers.naver.com

api 신청을 하고 등록을 진행한다.

 

등록이 완료되면 아래와 같은 ID와 Secret이 보여진다.

문서에 예시와 같이 적어서 테스트를 진행해 본다.

테스트 화면 (Talend api Tester를 이용하였다.)

 

 

네이버 API를 이용하는 자바 코드

    @GetMapping("/naver")
    public String naver(){
        // 검색할 조건 encoding
        String query = "갈비집";
        String encode = Base64.getEncoder().encodeToString(query.getBytes(StandardCharsets.UTF_8));
        log.info("encoding: {}", encode);
    // https://openapi.naver.com/v1/search/local.json
    // ?query=\xEA\xB3\xA0\xEA\xB8\xB0\xEC\xA7\x91
    // &display=10
    // &start=1
    // &sort=random
        URI uri = UriComponentsBuilder
                .fromUriString("https://openapi.naver.com")
                .path("/v1/search/local.json")
//                .queryParam("query", "encode")
//                직접 넣어주는 방법
                .queryParam("query", "IT")
                .queryParam("display", 10)
                .queryParam("start", 1)
                .queryParam("sort", "random")
                // UTF-8로 인코딩
                .encode(Charset.forName("UTF-8"))
                .build()
                .toUri();

        RestTemplate restTemplate = new RestTemplate();

        // header 값 추가 get으로 요청하기 때문에 Void로 받는다.
        RequestEntity<Void> req = RequestEntity
                .get(uri)
                .header("X-Naver-Client-Id","발급받은 ID")
                .header("X-Naver-Client-Secret", "발급받은 Secret")
                .build();

        ResponseEntity<String> result = restTemplate.exchange(req, String.class);
        return result.getBody();
    }

 

확인

 

JSON 형식을 정렬

사이트

https://jsonformatter.curiousconcept.com/#

 

JSON Formatter & Validator

Format and validate JSON data so that it can easily be read by human beings.

jsonformatter.curiousconcept.com

반응형