[Java/Spring] Server to Server (API exchange)

Hyeri Park·2022년 8월 12일
0
post-thumbnail

server 연결시 GET/POST 방법을 학습해 보았다.
이젠 클라이언트 측에서 header 외 여러 가지 것들을 변환하여 보내는 방법을 알아보자!

1. exchange 메서드 (header)

모든 HTTP 요청 메소드를 지원하며 원하는 서버에 요청시켜줌

1) Client

(1) Apicontroller.java

package com.example.client.controller;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.client.model.UserRequestDto;
import com.example.client.model.UserResponseDto;
import com.example.client.service.RestTemplateService;

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

	private final RestTemplateService restTemplateService;
	
		
	public ApiController(RestTemplateService restTemplateService) {

		this.restTemplateService = restTemplateService;
	}
	
// ================== exchange ===========================
	@GetMapping("/hello")
	public UserResponseDto gethello() {
		restTemplateService.exchange();
		return new UserResponseDto();
	}
// ==================================================	
}

(2) RestTemplateService.java

package com.example.client.service;

import java.net.URI;

import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.example.client.model.UserRequestDto;
import com.example.client.model.UserResponseDto;

@Service
public class RestTemplateService {

	// ================ exchange ==============================
	// 원하는 헤더를 실어서 보낼 수 있음 
	public UserResponseDto exchange() {
		//http://localhost/api/server/user/{userId}/name/{userName}

			
			URI uri = UriComponentsBuilder
					.fromUriString("http://localhost:9090")
					.path("api/server/user/{userId}/name/{userName}")
					.encode()
					.build()
					.expand("100","ila") //순차적으로 파라미터넣기 
					.toUri();
				
			System.out.println(uri);		
			
			// http body -> object -> object mapper -> json -> rest template -> http body json
			// http body를 만들건데 object만 보낼거야 object mapper가 json을만들어서 rest template에 보내서 http body에 json으로 넣어줄것이다.
			
			UserRequestDto req = new UserRequestDto();
			req.setName("ila exchange");
			req.setAge(21);
			
			RequestEntity<UserRequestDto> requestEntity = RequestEntity
					.post(uri)
					.contentType(MediaType.APPLICATION_JSON)
					.header("x-authorization", "abcd")
					.header("custom-header","ffff")
					.body(req);
			
			RestTemplate restTemplate = new RestTemplate();
			ResponseEntity<UserResponseDto> response = restTemplate.exchange(requestEntity, UserResponseDto.class);
			return response.getBody();
			
	}

}

2) Server

(1) ServerApicontroller.java

package com.example.server.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.server.model.UserDto;

import lombok.extern.slf4j.Slf4j;

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

// ================== Post / exchange ===========================
	@PostMapping("user/{userId}/name/{userName}")
	public UserDto post(@RequestBody UserDto user, 
						@PathVariable int userId, 
						@PathVariable String userName,
						@RequestHeader("x-authorization") String authorization, //추가 
						@RequestHeader("custom-header") String customheader // 추가 
	) {
		log.info("userId : {}, userName : {} ", userId, userName);
		log.info("client req : {}",user);
		log.info("authorization : {}, customheader : {} ", authorization, customheader);
		return user;
	}
// ===================================================	

profile
Backend Developer

0개의 댓글