네로개발일기

개발자 네로의 개발 일기, 자바를 좋아합니다 !

'2022/01/13'에 해당되는 글 1건


반응형

[이전 글]

 

[Spring] RestTemplate / spring 에서 http 통신하는 법 / API 호출

🐝 Rest 서비스를 호출하는 방법 - RestTemplate Spring 3부터 지원, REST API 호출 이후 응답을 받을 때까지 기다리는 동기 방식 - AsyncRestTemplate Spring 4에 추가된 비동기 RestTemplate - WebClient Spring..

frogand.tistory.com

 

🌱 UriComponentsBuilder

org.springframework.web.util.UriComponentsBuilder를 사용하면 명확한 URI 문자열을 생성할 수 있다.

final String uri = "https://frogand.tistory.com";
final String uriWithParameter = UriComponentsBuilder.fromHttpUrl(uri)
                                    .path("/category/programming/ECMAScript6"
                                    .queryParam("page", 2)
                                    .toString();
// https://frogand.tistory.com/category/programming/ECMAScript6?page=2

 

예제) parameter가 있는 url로 HTTP GET Method 호출

public static List<DataDto> selectDataByMemberId(String memberId) {
    if (StringUtils.isEmpty(memberId)) {
        return null;
    }

    final String selectDataUrl = "http://localhost:8080" + "/api/Data";
    String httpUrl = UriComponentsBuilder.fromHttpUrl(selectDataUrl)
            .queryParam("memberId", memberId)
            .toUriString();

    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<List<DataDto>> userRecommendResponse = 
            restTemplate.exchange(
            httpUrl,
            HttpMethod.GET, 
            null, 
            new ParameterizedTypeReference<List<DataDto>>() {
            });

    return userRecommendResponse.getBody();
}

 

 

출처

https://stackoverflow.com/questions/8297215/spring-resttemplate-get-with-parameters

 

Spring RestTemplate GET with parameters

I have to make a REST call that includes custom headers and query parameters. I set my HttpEntity with just the headers (no body), and I use the RestTemplate.exchange() method as follows: HttpHead...

stackoverflow.com

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !