본문 바로가기
Spring

Server to Server의 연결 - get

by step 1 2021. 6. 26.
반응형

client 입장에서 서버에 통신하기 위해서 임의로 URL 생성하는 방법: UriComponentsBuilder

//        주소 만들기: http://localhost:8081/api/server/hello
        URI uri = UriComponentsBuilder
                .fromUriString("http://localhost:8081")
                .path("/api/server/hello")
                // 주소에 값을 넣는 방법: queryParam
                // http://localhost:8081/api/server/hello?name=steve&age=10
                .queryParam("name", "steve")
                .queryParam("age", 10)
                .encode()
                .build()
                .toUri();

RestTemplate으로 get 서버 통신하는 방법: getForEntity

RestTemplate restTemplate = new RestTemplate();
        // client가 되어 해당url의 서버를 호출한다. (get 방식, string으로 반환)
//        String result = restTemplate.getForObject(uri, String.class);

        // ResponseEntity 형식으로 호출
        //ResponseEntity<String> result = restTemplate.getForEntity(uri, String.class);
        ResponseEntity<UserResponse> result = restTemplate.getForEntity(uri, UserResponse.class);
        System.out.println(result.getStatusCode()); // 200 OK
        System.out.println(result.getBody()); // UserResponse(name=steve, age=10)

client에서 호출하는 코드

package com.example.client.contoller;

import com.example.client.dto.UserResponse;
import com.example.client.service.RestTemplateService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/client")
public class ApiController {

    private final RestTemplateService restTemplateService;

    public ApiController(RestTemplateService restTemplateService) {
        this.restTemplateService = restTemplateService;
    }

    @GetMapping("")
    public UserResponse getHello(){
        // 서버로 호출
        return restTemplateService.hello();
    }
}

서버에서 받는 코드

@RestController
@RequestMapping("/api/server")
public class ServerApiController {

    @GetMapping("/hello")
    public User hello(@RequestParam String name, @RequestParam int age){
        User user = new User();
        user.setName(name);
        user.setAge(age);
        return user;
    }
}

 

확인

 

테스트를 진행하기 위해서는 서버를 2개 띄워줘야하고 port번호를 서로 다르게 해주어야 한다.

반응형

'Spring' 카테고리의 다른 글

Server to Server의 연결 - header 값 지정하는 방법  (0) 2021.06.26
Server to Server의 연결 - post  (0) 2021.06.26
Exception 처리  (0) 2021.06.19
Custom Validation  (0) 2021.06.19
Validation  (0) 2021.06.19