[Java/Spring] Server to Server (API - POST)

Hyeri Park·2022년 8월 12일
0

JAVA/Spring 기초

목록 보기
19/22
post-thumbnail

1. 기본 작업

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 {
	
	
	//@Autowired //옛날에는 Autowired를 사용했는데, 요즘엔 생성자 주입방식으로 아래와 같이 사용한다.
	// default 생성자 = final 
	private final RestTemplateService restTemplateService;
	
	
	
	public ApiController(RestTemplateService restTemplateService) {

		this.restTemplateService = restTemplateService;
	}

	
// ================== POST ===========================
	@PostMapping("/hello")
	public UserRequestDto post() {
		return restTemplateService.post();
	}
// ==================================================	
}

(2) RestTemplateService.java

package com.example.client.service;

import java.net.URI;

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 {

// ==================== POST ===========================
	
	//http://localhost/api/server/user/{userId}/name/{userName}
	public UserRequestDto post() {
		
		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("ilapost");
		req.setAge(21);
		
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<UserRequestDto> response = restTemplate.postForEntity(uri, req, UserRequestDto.class);
		System.out.println(response.getStatusCode());
		System.out.println(response.getHeaders());
		System.out.println(response.getBody());
		
		return response.getBody();
		
	};


}

(3) UserRequestDto.java

package com.example.client.model;

import lombok.Data;

@Data
public class UserRequestDto {
	private String name;
	private int age;
}

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.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 ===========================
	@PostMapping("user/{userId}/name/{userName}")
	public UserDto post(@RequestBody UserDto user, @PathVariable int userId, @PathVariable String userName) {
		log.info("userId : {}, userName : {} ", userId, userName);
		log.info("client req : {}",user);
		return user;
	}
// ===================================================	
}

서버 재실행

  • Server console

  • Client console

profile
Backend Developer

0개의 댓글