Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 페이징
- 구멍가게코딩단
- 코드로배우는스프링웹프로젝트
- network configuration
- 네트워크 설정
- /etc/network/interfaces
- 리눅스
- 알파회계
- GIT
- 자료구조와 함께 배우는 알고리즘 입문
- 처음 만나는 AI수학 with Python
- 스프링부트핵심가이드
- 친절한SQL튜닝
- 목록처리
- 서버설정
- 데비안
- 자바편
- 스프링 시큐리티
- 선형대수
- Kernighan의 C언어 프로그래밍
- baeldung
- resttemplate
- iterator
- 코드로배우는스프링부트웹프로젝트
- 티스토리 쿠키 삭제
- 이터레이터
- 자료구조와함께배우는알고리즘입문
- 처음 만나는 AI 수학 with Python
- d
- ㅒ
Archives
- Today
- Total
bright jazz music
WebClient 02 : POST 본문
요약
- WebClientPostService.java를 생성하여 WebClient 요청, 응답 수신 로직을 작성한다.
- 응답을 브라우저에서 확인할 수 있도록 WebClientController.java 파일에 경로를 작성한다.
- 이해에 용이하도록 요청 측 controller - 요청측 service - 수신 측 controller - 결과 순으로 내요을 구성하였다.
1. WebClientController.java 작성(요청 측 컨트롤러 http://localhost:8080)
//WebClientController.java
package com.project.base.controller;
import com.project.base.domain.MemberDto;
import com.project.base.service.WebClientGetService;
import com.project.base.service.WebClientPostService;
import org.springframework.http.ResponseEntity;
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;
@RestController
@RequestMapping("/web-client")
public class WebClinetController {
private final WebClientGetService webClientGetService;
private final WebClientPostService webClientPostService;
public WebClinetController(WebClientGetService webClientGetService, WebClientPostService webClientPostService) {
this.webClientGetService = webClientGetService;
this.webClientPostService = webClientPostService;
}
/**
* POST
*/
@GetMapping("post-with-param-and-body")
public ResponseEntity<MemberDto> postWithParamAndBody() {
return webClientPostService.postWithParamAndBody();
}
@GetMapping("post-with-header")
public ResponseEntity<MemberDto> postWithHeader() {
return webClientPostService.postWithHeader();
}
}
2. WebClientPostService.java 작성(요청 측 서비스)
//WebClientPostService.java
package com.project.base.service;
import com.project.base.domain.MemberDto;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
@Service
public class WebClientPostService {
public ResponseEntity<MemberDto> postWithParamAndBody() {
WebClient webClient = WebClient.builder()
.baseUrl("http://localhost:9090")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
MemberDto memberDto = new MemberDto();
memberDto.setName("dognails");
memberDto.setEmail("dognails@gmail.com");
memberDto.setOrganization("dognails company");
return webClient.post().uri(uriBuilder -> uriBuilder.path("/api/v1/crud-api")
.queryParam("name", "catnails")
.queryParam("email", "catnails@gmail.com")
.queryParam("organization", "catnails company")
.build())
.bodyValue(memberDto)
.retrieve()
.toEntity(MemberDto.class)
.block();
}
public ResponseEntity<MemberDto> postWithHeader() {
WebClient webClient = WebClient.builder()
.baseUrl("http://localhost:9090")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
MemberDto memberDto = new MemberDto();
memberDto.setName("dognails");
memberDto.setEmail("dognails@gmail.com");
memberDto.setOrganization("dognails company");
return webClient.post()
.uri(uriBuilder -> uriBuilder.path("/api/v1/crud-api/add-header")
.build())
.bodyValue(memberDto)
.header("my-header", "catnails API")
.retrieve()
.toEntity(MemberDto.class)
.block();
}
}
3. 수신 측 서버 컨트롤러 작성(http://localhost:9090)
요청을 받는 서버 설정
//외부 API 역할을 하는 서버 => server.port=9090
package com.project.base.controller;
import com.project.base.domain.MemberDto;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/crud-api")
public class CrudController {
/* POST: RequestParameter와 RequestBody를 받는 경우. (귀찮아서 한 번에 해버리는 예시) */
@PostMapping
public ResponseEntity<MemberDto> getMember(@RequestBody MemberDto request, @RequestParam String name,
@RequestParam String email, @RequestParam String organization) {
System.out.println("## request.getName() = " + request.getName());
System.out.println("## request.getEmail() = " + request.getEmail());
System.out.println("## request.getOrganization() = " + request.getOrganization());
MemberDto memberDto = new MemberDto(name, email, organization);
return ResponseEntity.status(HttpStatus.OK).body(memberDto);
}
/* POST: 임의의 HTTP 헤더를 RequestBody와 함께 받는 경우*/
@PostMapping(value = "/add-header")
public ResponseEntity<MemberDto> addHeader(@RequestHeader("my-header") String header, @RequestBody MemberDto memberDto) {
System.out.println(header);
return ResponseEntity.status(HttpStatus.OK).header(header).body(memberDto);
}
}
4. 결과
4.1 http://localhost:8080/web-client/post-with-param-and-body 요청
4.2 http://localhost:8080/web-client/post-with-header
'Framework > Spring' 카테고리의 다른 글
WebClient 01 : GET (0) | 2023.03.06 |
---|---|
RestTemplate 02 : 커넥션 풀(connection pool) 추가 (0) | 2023.03.06 |
RestTemplate 01 : 파라미터 없는 GET 요청 (0) | 2023.03.02 |
[bootBoard] N:1(다대일) 연관관계: 11-7. 목록화면에서 검색 처리 (0) | 2022.10.12 |
[bootBoard] N:1(다대일) 연관관계: 11-6. JPQLQuery로 Page<Object[]> 처리: sort 처리 / count 처리 (0) | 2022.10.11 |
Comments