nhnacademy-be6-code-quest / Role

This Team Role
0 stars 0 forks source link

naver book api #9

Open InJunKangW opened 2 weeks ago

InJunKangW commented 2 weeks ago

구현 자체는 성공해서 테스트용 코드는 작성했는데, 지피티한테 물어보고 한 게 90프로 이상이라 자세한 내용은 더 공부하고 적어보겠습니다

InJunKangW commented 2 weeks ago

package com.nhnacademy.naver.controller;

import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.nhnacademy.naver.BookDto; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.json.JSONObject; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder;

@Slf4j @Controller @RequestMapping("/test") @RequiredArgsConstructor public class NaverController {

private final RestTemplate restTemplate;

@GetMapping
public String test(Model model) throws JsonProcessingException {
    log.error("test called");

    String clientId = "N9lkNYu0YvTUgd56Weib"; // 네이버 api 등록시 생긴 클라이언트 id
    String clientSecret = "dQ_IKQZM55";  // 네이버 api 등록시 생긴 클라이언트 비밀번호 (실제 제가 localhost:8080에 연결되게 등록한거라 확실하진 않지만 실제로 구동해보시면 돌아 갈 것 같습니다)

    String rawString = "이해";  // 검색할 제목
    byte[] bytes = rawString.getBytes(StandardCharsets.UTF_8);

    String utf8EncodedString = new String(bytes, StandardCharsets.UTF_8);

    URI uri = UriComponentsBuilder
            .fromUriString("https://openapi.naver.com")
            .path("/v1/search/book_adv.json")
            .queryParam("d_titl",utf8EncodedString)
           검색할 제목의 utf-8 인코딩 된 값 - 주석처리
         .queryParam("lsbn") - 주석처리
            .queryParam("start", 1)
            .queryParam("display", 5)
            .queryParam("sort", "sim")
            .encode()
            .build()
            .toUri();

    RequestEntity<Void> req = RequestEntity
            .get(uri)
            .header("X-Naver-Client-Id", clientId)
            .header("X-Naver-Client-Secret", clientSecret)
            .build();

    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(req, String.class);
    ObjectMapper objectMapper = new ObjectMapper();

    String responseBody = responseEntity.getBody();
    JsonNode rootNode = objectMapper.readTree(responseBody);
    JsonNode itemsNode = rootNode.path("items");

    List<BookDto> bookList = new ArrayList<>();
    if (itemsNode.isArray()) {
        for (JsonNode itemNode : itemsNode) {
            BookDto bookDto = objectMapper.treeToValue(itemNode, BookDto.class);
            bookList.add(bookDto);
        }
    }

    model.addAttribute("bookList", bookList);
    return "test";
}

}

//========================= 테스트용 view ========

<!DOCTYPE html>

Title

=====================pom.xml에 추가할 내용

org.json json 20240303