study/spring | java

[Select Shop] 셀렉샵 만들기 3. java에 네이버 API 적용하기

_드레 2021. 6. 6. 19:05

1. 자바 코드 확인하기

2. 스프링 프로젝트 준비하기

3. 검색 실행하고 결과 확인하기 

 

[0] IntelliJ 새 프로젝트 

- H2, lombok, spring Web, JPA, mySQL 추가

- auto import, annotation 설정 (ctrl+alt+s)

* auto import

    └ Insert imports on paste : Always

    └ Add unambiguous imports on the fly (checked)

* annotation 

    └ compiler 검색 - Annotation Processors

          Enable annotation processing (checked) 

 

[1] NaverShopSearch.java 클래스

src > main > java > com.xxx.xxx > utils(프로젝트 생성) > NaverShopSearch 클래스 생성

public class NaverShopSearch {
    public String search() {
		//돌려줄 String 없어서 오류나는 상태
    }

    public static void main(String[] args) {
        NaverShopSearch naverShopSearch = new NaverShopSearch();
        naverShopSearch.search();
    }
}

 

[2]ARC에서 생성된 코드 붙여넣기

public class NaverShopSearch {
    public String search() {
        RestTemplate rest = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Naver-Client-Id", "GuziZfI6S6a2kj4i6n1h");
        headers.add("X-Naver-Client-Secret", "czg3oFpmZg");
        String body = "";

        HttpEntity<String> requestEntity = new HttpEntity<String>(body, headers);
        ResponseEntity<String> responseEntity = rest.exchange("https://openapi.naver.com/v1/search/shop.json?query=apple", HttpMethod.GET, requestEntity, String.class);
        HttpStatus httpStatus = responseEntity.getStatusCode();
        int status = httpStatus.value();
        String response = responseEntity.getBody();
        System.out.println("Response status: " + status);
        System.out.println(response);

        return response;
    }

    public static void main(String[] args) {
        NaverShopSearch naverShopSearch = new NaverShopSearch();
        naverShopSearch.search();
    }
}

body라는 String을 만들어서 응답을 받으면 requestEntity 라는 곳에 body를 같이 넣어준다. 

body 안에 우리가 응답받은 결과물이 들어가는것.

 

Status 인쇄하고 response 찍어보기

 

 

 

서버 돌리면 ARC에서처럼 잘 나온다. 

검색어 한글로 바꿔도 잘 나옴 UTF-8 코딩 spring이 해줘서