1+ package com .closetnangam .be .global .external .naver .service ;
2+
3+ import org .springframework .beans .factory .annotation .Value ;
4+ import org .springframework .http .*;
5+ import org .springframework .stereotype .Service ;
6+ import org .springframework .web .client .RestTemplate ;
7+ import org .springframework .web .util .UriComponentsBuilder ;
8+
9+ import java .net .URI ;
10+ import java .nio .charset .StandardCharsets ;
11+
12+ @ Service
13+ public class NaverApiService {
14+
15+ // ⚠️ 중요: yml 경로(spring.security.oauth2.client.registration.naver...)와 완벽하게 싱크를 맞춥니다!
16+ @ Value ("${spring.security.oauth2.client.registration.naver.client-id}" )
17+ private String clientId ;
18+
19+ @ Value ("${spring.security.oauth2.client.registration.naver.client-secret}" )
20+ private String clientSecret ;
21+
22+ // 1. 메서드 이름을 쇼핑 검색에 맞게 수정했습니다.
23+ public String searchShop (String keyword ) {
24+ RestTemplate restTemplate = new RestTemplate ();
25+
26+ // 2. path를 블로그(.blog)에서 쇼핑(.shop)으로 변경했습니다!
27+ URI targetUri = UriComponentsBuilder
28+ .fromUriString ("https://openapi.naver.com" )
29+ .path ("/v1/search/shop.json" )
30+ .queryParam ("query" , keyword )
31+ .queryParam ("display" , 10 )
32+ .encode (StandardCharsets .UTF_8 )
33+ .build ()
34+ .toUri ();
35+
36+ // 2. 네이버 API 필수 헤더 설정 (아주 정확하게 잘 짜셨습니다!)
37+ HttpHeaders headers = new HttpHeaders ();
38+ headers .set ("X-Naver-Client-Id" , clientId );
39+ headers .set ("X-Naver-Client-Secret" , clientSecret );
40+ headers .setContentType (MediaType .APPLICATION_JSON );
41+
42+ HttpEntity <String > entity = new HttpEntity <>(headers );
43+
44+ // 3. API 호출 및 응답 받기
45+ ResponseEntity <String > response = restTemplate .exchange (
46+ targetUri ,
47+ HttpMethod .GET ,
48+ entity ,
49+ String .class
50+ );
51+
52+ // 4. 결과 반환
53+ if (response .getStatusCode () == HttpStatus .OK ) {
54+ return response .getBody ();
55+ } else {
56+ throw new RuntimeException ("네이버 쇼핑 API 호출 실패: " + response .getStatusCode ());
57+ }
58+ }
59+ }
0 commit comments