본문 바로가기
🍃SpringFramework/SpringBoot

[SpringBoot] 07. Server to Server

by inbeom 2023. 8. 20.
728x90
반응형

 💡 Client

Controller

@RestController
@RequestMapping("/api/client")
public class ApiController {
	private final RestTemplateService restTemplateService;
	public ApiController(RestTemplateService restTemplateService) {
		this.restTemplateService = restTemplateService;
	}

	@GetMapping("/hello")
	public Req<UserResponse> getHello(){
		return restTemplateService.genericExchange();
	}
}

사용자가 localhost:9090/api/client/hello를 입력하면 restTemplateService클래스의 genericExchange()메서드 실행

 

Service

public UserResponse exchange() {
	URI uri = UriComponentsBuilder
		.fromUriString("[<http://localhost:9090>](<http://localhost:9090/>)")
		.path("/api/server/user/{userId}/name/{userName}")
		.encode()
		.build()
		.expand(100, "steve")
		.toUri();
	System.out.println(uri);

	// http body -> object -> object mapper -> json -> rest template -> http body json
	UserRequest req = new UserRequest();
	req.setName("steve");
	req.setAge(10);
	RequestEntity<UserRequest> requestEntity = RequestEntity
		.post(uri)
		.contentType(MediaType.APPLICATION_JSON)
		.header("x-authorization", "abcd")
		.header("custom-header", "fffff")
		.body(req);

	RestTemplate restTemplate = new RestTemplate();
	ResponseEntity<UserResponse> response = restTemplate.exchange(requestEntity, UserResponse.class);
	return response.getBody();
}

UriComponentsBuilder를 이용하여 Uri를 만들고, RequestEntity에 uri, type, header, body를 설정함.

ResponseEntity타입의 RestTemplate 객체를 만들어 exchange()로 전송해 response에 결과값을 받아옴.

 

💡 Server

Controller

@Slf4j
@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;
	}

	@PostMapping("/user/{userId}/name/{userName}")
	public Req post(
		HttpEntity entity,
		@RequestBody Req user,
		@PathVariable int userId,
		@PathVariable String userName,
		@RequestHeader("x-authorization") String authorization,
		@RequestHeader("custom-header") String customHeader
	) {

		[log.info](<http://log.info/>)("req : {}", entity.getBody());
		[log.info](<http://log.info/>)("userId : {}, userName : {}", userId, userName);
		[log.info](<http://log.info/>)("autn : {}, customH : {}", authorization, customHeader);
		[log.info](<http://log.info/>)("client req : {}", user);
		Req response = new Req<>();
		response.setHeader( new Req.Header() );
		response.setResBody( user.getResBody() );
		return response;
	}
}

Client에서 보내온 데이터들을 HttpEntity, RequestBody, PathVariable, RequestHeader로 받고 값을 처리하여 리턴.

 

 💡 Naver-api

네이버 검색 API 사용하여 JSON값 받아오기!!

(https://developers.naver.com/apps/#/myapps/lfor1L7Hwpv7F4u9_0cG/overview)

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

	// <https://openapi.naver.com/v1/search/local.json>
	// ?query=%EC%A3%BC%EC%8B%9D
	// &display=10
	// &start=1
	// &sort=random

	@GetMapping("/naver")
	public String naver() {

		String query = "카페";
		URI uri = UriComponentsBuilder     // uri 세팅
			.fromUriString("<https://openapi.naver.com>")
			.path("/v1/search/local.json")
			.queryParam("query", query)
			.queryParam("display", 10)
			.queryParam("start", 1)
			.queryParam("sort", "random")
			.encode(Charset.forName("UTF-8"))
			.build()
			.toUri();

		//log.info](<https://log.info/>)("uri : {}", uri);
		RestTemplate restTemplate = new RestTemplate();

		RequestEntity req = RequestEntity // uri와 보낼 해더 정보
			.get(uri)
			.header("X-Naver-Client-Id", "Client ID 비밀!")
			.header("X-Naver-Client-Secret", "Client Secret 비밀!")
			.build();

		// 주어진 메서드의 결과를 ResponseEntity타입의 result로 반환받음.
		ResponseEntity result = restTemplate.exchange(req, String.class);
		return result.getBody();
	}
}

네이버 OpenApi형식대로 URI에 uri, path, parameter, encode넣고 생성.

RequestEntity객체에 uri와 header에 개인 애플리케이션 id, secret값 넣어서 생성.

restTemplate.exchange에 위에서 만든 RequestEntity태워 보내고, ResponseEntity타입 객체로 값 반환.

 

결과 화면

 

728x90
반응형