client의 RestTemplateService.java
post 부분 넣기
package com.example.client.service;
import com.example.client.dto.UserRequest;
import com.example.client.dto.UserResponse;
import org.apache.catalina.User;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
@Service
public class RestTemplateService {
//http://localhost/api/server/hello
//response
public UserResponse hello(){
URI uri = UriComponentsBuilder
.fromUriString("http://localhost:9090")
.path("/api/server/hello")
.queryParam("name","Hyerin")
.queryParam("age",26)
.encode()
.build()
.toUri();
System.out.println(uri.toString());
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<UserResponse> result = restTemplate.getForEntity(uri,UserResponse.class);
System.out.println(result.getStatusCode());
System.out.println(result.getBody());
return result.getBody();
}
public UserResponse post(){
//http://localhost:9090/api/server/user/{userId}/name{userName}
URI uri = UriComponentsBuilder
.fromUriString("http://localhost:9090")
.path("/api/server/user/{userId}/name{userName}")
.encode()
.build()
.expand(100) //pathvariable 하나씩 매칭
.expand("steve")
.toUri();
System.out.println(uri);
// post이기 때문에 http body가 필요하다
// http body -> object -> object mapper -> json으로 바꿈 -> rest template -> http body json에 넣어줌
UserRequest req = new UserRequest();
req.setName("steve");
req.setAge(10);
//Rest template로 쏘기
}
}
dto - UserRequest 만들기
package com.example.client.dto;
public class UserRequest {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "UserResponse{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
post로 보낼 때도 마찬가지로,
1. 주소 만들기
2. 내가 보내고 싶은 Request body data를 json으로 만드는 것이 아니라 object로 만들기
UserRequest req = new UserRequest();
3. object mapper가 자연적으로 json으로 바꿔주고
4. rest template에서 body에 json을 넣어서 쏠 것이다.
5. 그리고 응답을 무엇으로 받을 지 지정하면 된다.
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<UserResponse> response = restTemplate.postForEntity(uri,req,UserResponse.class);
package com.example.client.service;
import com.example.client.dto.UserRequest;
import com.example.client.dto.UserResponse;
import org.apache.catalina.User;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
@Service
public class RestTemplateService {
//http://localhost/api/server/hello
//response
public UserResponse hello(){
URI uri = UriComponentsBuilder
.fromUriString("http://localhost:9090")
.path("/api/server/hello")
.queryParam("name","Hyerin")
.queryParam("age",26)
.encode()
.build()
.toUri();
System.out.println(uri.toString());
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<UserResponse> result = restTemplate.getForEntity(uri,UserResponse.class);
System.out.println(result.getStatusCode());
System.out.println(result.getBody());
return result.getBody();
}
public UserResponse post(){
//http://localhost:9090/api/server/user/{userId}/name{userName}
URI uri = UriComponentsBuilder
.fromUriString("http://localhost:9090")
.path("/api/server/user/{userId}/name/{userName}") //PathVariable 처리하는 방법
.encode()
.build()
.expand(100,"steve") //pathvariable 하나씩 매칭
.toUri();
System.out.println(uri);
// post이기 때문에 http body가 필요하다
// http body -> object -> object mapper -> json으로 바꿈 -> rest template -> http body json에 넣어줌
UserRequest req = new UserRequest();
req.setName("steve");
req.setAge(10);
//Rest template로 쏘기
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<UserResponse> response = restTemplate.postForEntity(uri,req,UserResponse.class);
//uri 라는 주소에, req(request body)를 만들어서, 응답은 UserResponse로 받을 것이라는 뜻
System.out.println(response.getStatusCode());
System.out.println(response.getHeaders());
System.out.println(response.getBody());
return response.getBody();
}
}
서버에서 받아주는 것을 만들어보자
package com.example.server.controller;
import com.example.server.dto.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@RequestMapping("/api/server")
public class ServerApiController {
@GetMapping("/hello")
public User hello(@RequestParam String name, @RequestParam int age){
User user = new User();
user.setAge(age); //echo 방식으로 동작할 것이기 때문에 age, name 넣자
user.setName(name);
return user;
}
@PostMapping("/user/{userId}/name/{userName}") //변경되는 값을 변수로 매칭해주자 (아래 @PathVariable로)
public User post(@RequestBody User user,@PathVariable int userId,@PathVariable String userName){ //@RequestBody로 User를 받는다
log.info("client req : {}",user); //user의 toString이 괄호에 들어간다는 뜻
log.info("userId : {}, userName : {}",userId,userName);
return user;
}
}
package com.example.client.controller;
import com.example.client.dto.UserResponse;
import com.example.client.service.RestTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
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("/hello")
public UserResponse getHello(){
return restTemplateService.post(); //post 메소드 호출하기
}
}
결과
서버 측 결과
서버가 어떻게 응답을 줄 지 모르겠을 때,
어떠한 값이 잘못 와서 뭔가 오류가 난 것 같을 때,
String으로 받아보자!
public void post(){
URI uri = UriComponentsBuilder
.fromUriString("http://localhost:9090")
.path("/api/server/user/{userId}/name/{userName}")
.encode()
.build()
.expand(100,"steve")
.toUri();
System.out.println(uri);
UserRequest req = new UserRequest();
req.setName("steve");
req.setAge(10);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(uri,req,String.class);
System.out.println(response.getStatusCode());
System.out.println(response.getHeaders());
System.out.println(response.getBody());
//return response.getBody(); 없애버렷
}
package com.example.client.controller;
import com.example.client.dto.UserResponse;
import com.example.client.service.RestTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
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("/hello")
public UserResponse getHello(){
restTemplateService.post();
return new UserResponse();
}
}
결과
json 형태의 toString이 넘어옴(문자열로)
'Spring' 카테고리의 다른 글
Naver 지역 검색 API 사용하기 (0) | 2022.07.18 |
---|---|
Server to server - header (0) | 2022.07.16 |
Server to server - GET (0) | 2022.06.26 |
Spring Boot - Interceptor (0) | 2022.06.20 |
Spring boot - Filter (0) | 2022.06.18 |