[Spring Boot] OPEN API 호출값 받아오기

Jayden ·2022년 12월 28일
0
package com.example.demo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;

import lombok.extern.slf4j.Slf4j;

import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;


@Slf4j
@RestController
public class ApiController {

    @CrossOrigin(originPatterns = "http://localhost:3000")
    @GetMapping("/kakao/{keyword}")
    public String callApi(@PathVariable String keyword) throws JsonProcessingException {


        ByteBuffer buffer = StandardCharsets.UTF_8.encode(keyword);
        String encode = StandardCharsets.UTF_8.decode(buffer).toString();
        System.out.println(encode);

        URI uri = UriComponentsBuilder
                .fromUriString("https://dapi.kakao.com/v3/search")
                .path("/book")
                .queryParam("query", encode)
                .encode()
                .build()
                .toUri();


        RestTemplate restTemplate = new RestTemplate();

        // 아래는 헤더를 넣기 위함
        RequestEntity<Void> req = RequestEntity
                .get(uri)
                .header("Authorization", "KakaoAK ****************") //해당 부분에 인증키 입력하기
                .build();

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

        log.info("uri : {} " , uri);
        log.info("result : {}", result);
       // System.out.println(result.getBody().getClass());
 

        return result.getBody();
     /*json 문자열로 리턴하므로 프론트엔드에서 fetch 함수
       다음과 같이 사용할수 있다.
     
     예)
      fetch(`http://localhost:8080/kakao/${keyword}`)
        .then((response) => response.json())
        .then((data) => {setList(data.documents)}
 
        );
     */
     

    }
}


profile
프론트엔드 개발자

0개의 댓글