반응형

 

 

Rest API 서버에 요청을 해서 해당 값을 Controller에서 사용할 때

 

RestTemplate를 이용해서 요청을 보낼 수 있다.

* 현재는 Spring이 RestTemplate보다는 WebClient를 지원

 

@GetMapping("/test3")
public void test3() {
    // 요청할 URL 만들기
    URI uri = UriComponentsBuilder
            .fromUriString("http://localhost:8080")
            .path("/api/test")
            .build()
            .toUri();

    RestTemplate rt = new RestTemplate();
    // HTTP GET, 응답을 객체로 받기.
    String s1 = rt.getForObject(uri, String.class);

    // HTTP GET, 응답을 ResponseEntity 로 받기.
    ResponseEntity<String> responseEntity = rt.getForEntity(uri, String.class);
    System.out.println(responseEntity.getStatusCode());
    System.out.println(responseEntity.getBody());

    // HTTP GET, 응답을 JSON 을 받을 때
    // dto 객체로 받는다.
    ResponseEntity<User> responseEntity1 = rt.getForEntity(uri, User.class);


}

 

URL를 만든 후 RestTemplate를 이용하여 요청을 한다.

 

 

 

 

URI uri = UriComponentsBuilder
        .fromUriString("http://localhost:8080")
        .path("/api/test")
        .queryParam("name", "cha")
        .queryParam("age", 25)
        .build()
        .toUri();

UriComponentsBuilder의 queryParam() 메서드를 이용해 Parameter 값을 요청해줄 수 있다.

 

 

 

 

URI uri = UriComponentsBuilder
        .fromUriString("http://localhost:8080")
        .path("/api/test/{name}/{age}")
        .encode()
        .build()
        .expand("cha", 30)
        .toUri();

UriComponentsBuilder의 expand() 메서드를 이용해 PathVariable 값을 요청해줄 수 있다.

 

 

 

 

 

RestTemplate rt = new RestTemplate();
// HTTP POST, 서버에 객체를 보내서 생성하기
User user = new User("cha",33);
// uri, request 객체, response type
ResponseEntity<User> userResponseEntity = rt.postForEntity(uri, user, User.class);

POST 요청 

서버의 명세를 보고 맞게 dto 를 작성하면 된다.

 

 

 

 


RequestEntity<User> request = RequestEntity
        .post(uri)
        .contentType(MediaType.APPLICATION_JSON)
        .header("headerDummy", "asdf")
        .body(new User("user",22));

RestTemplate rt1 = new RestTemplate();
ResponseEntity<User> responseEntity = rt1.exchange(request, User.class);

HTTP header를 커스텀해서 요청을 보낼 수도 있다.

헤더를 추가할 경우 RestTemplate의 exchange() 메서드를 사용

 

 

 


kakao Oauth 요청

 

@GetMapping("/complete")
public String complete(@RequestParam String code){
    System.out.println(code);

    // uri
    URI uri = UriComponentsBuilder
            .fromUriString("https://kauth.kakao.com/oauth/token")
            .encode(StandardCharsets.UTF_8)
            .build()
            .toUri();

    // header
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("Content-type","application/x-www-form-urlencoded;charset=utf-8");

    // body
    MultiValueMap<String, String> map = new LinkedMultiValueMap();
    map.add("grant_type" ,"authorization_code" );
    map.add("client_id","================" );
    map.add("redirect_uri","http://localhost:8080/complete" );
    map.add("code", code );

    // Header + body
    HttpEntity<Map<String, String>> httpEntity = new HttpEntity(map, httpHeaders);

    RestTemplate rt = new RestTemplate();
    ResponseEntity<HashMap> responseEntity = rt.exchange(uri, HttpMethod.POST, httpEntity, HashMap.class);
    responseEntity.getHeaders().forEach((k, v) -> System.out.println(k + " " + v));
    responseEntity.getBody().forEach((k, v) -> System.out.println(k + " " + v));

    return "completion";

 

 

 

 

 

네이버 api 사용

 

URI uri = UriComponentsBuilder
        .fromUriString("https://openapi.naver.com/v1/search/book.json")
        .queryParam("query", word)
        .queryParam("display", 20)
        .queryParam("sort", "sim")
        .encode(StandardCharsets.UTF_8)
        .build()
        .toUri();

RequestEntity requestEntity = RequestEntity
        .post(uri)
        .header("X-Naver-Client-Id", "아이디")
        .header("X-Naver-Client-Secret", " 키 ")
        .body(" ");

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<NaverBook> responseEntity = restTemplate.exchange(requestEntity, NaverBook.class);

RequestEntity

 

HttpEntity, HttpHeaders를 사용하지 않고

header, body, contentType 을 좀 더 편하게 만들어줄 수 있다.

 

 


 

정리

 

UriComponentsBuilder: 요청할 uri를 만든다.

RequestEntity: 요청[HTTP header, body]을 만들고 RestTemplate으로 요청한다.
ResponseEntity: 응답[HTTP header, body]을 RestTemplate으로부터 받아 사용한다.
RestTemplate: HTTP 프로토콜을 이용해서 서버에 요청, 전달받은 응답을 사용할 수 있게 해준다.

 

 

반응형

+ Recent posts