[내배캠/TIL(7/18)]Spring에서 외부 api와 통신하기-1

손홍서·2022년 7월 18일
1

Spring

목록 보기
22/24

day60 TIL

spring에서도 외부 api를 사용할 일이 있어 어떻게 사용하면 좋을지 간단히 코드를 정리하였다.
이러한 틀을 바탕으로 앞으로 응용해서 외부 api를 만들어 통신을 할 예정이다.

		String testurl = "http://localhost:5000/test";

        RestTemplate rest = new RestTemplate();
        
        //필요한 header와 body를 할당
        HttpHeaders headers = new HttpHeaders();
        String body = "";
		
        //요청을 만든다.
        HttpEntity<String> requestEntity = new HttpEntity<String>(body, headers);

		//응답을 받아온다.
        ResponseEntity<String> responseEntity = rest.exchange(testurl, HttpMethod.GET, requestEntity, String.class);

		//상태코드
        HttpStatus httpStatus = responseEntity.getStatusCode();
        int status = httpStatus.value();

		//받아온 데이터
        String response = responseEntity.getBody();

        return response;
profile
Hello World!!

0개의 댓글