2.2. retrieve()
retrieve() ๋ฉ์๋๋ ์๋ต ๋ณธ๋ฌธ(response body)๋ฅผ ๊ฐ์ ธ์์ ๋์ฝ๋ฉํ๋ ๊ฐ์ฅ ๊ฐ๋จํ ๋ฐฉ๋ฒ์ด๋ค. ๋ค์ ์์ ๋ ์ด๋ฅผ ์ํํ๋ ๋ฐฉ๋ฒ์ด๋ค:
Java:
WebClient client = WebClient.create("https://example.org");
Mono<Person> result = client.get()
.uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Person.class);
Kotlin:
val client = WebClient.create("https://example.org")
val result = client.get()
.uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
.retrieve()
.awaitBody<Person>()
๋ํ ์๋ต์ผ๋ก๋ถํฐ ๋์ฝ๋ฉ๋ ๊ฐ์ฒด ์คํธ๋ฆผ์ ์ป์ ์๋ ์๋ค.
Java:
Flux<Quote> result = client.get()
.uri("/quotes").accept(MediaType.TEXT_EVENT_STREAM)
.retrieve()
.bodyToFlux(Quote.class);
Kotlin:
val result = client.get()
.uri("/quotes").accept(MediaType.TEXT_EVENT_STREAM)
.retrieve()
.bodyToFlow<Quote>()
๊ธฐ๋ณธ์ ์ผ๋ก 4xx ๋๋ 5xx ์ํ ์ฝ๋(status code)๋ก ์๋ตํ๋ฉด WebClientResponseException ํน์
WebClientResponseException.BadRequest, WebClientResponseException.NotFound ๋ฑ๊ณผ ๊ฐ์ ๊ฐ HTTP ์ํ์ ๋ง๋
์์ธ๋ฅผ ๋์ง๋ค. ๋ํ onStatus ๋ฉ์๋๋ฅผ ์ฌ์ฉํ์ฌ ๊ฒฐ๊ณผ ์์ธ๋ฅผ ์ปค์คํฐ๋ง์ด์งํ ์ ์๋ค. ๋ค์์ ๊ทธ ์์ ๋ค:
Java:
Mono<Person> result = client.get()
.uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(HttpStatus::is4xxClientError, response -> ...)
.onStatus(HttpStatus::is5xxServerError, response -> ...)
.bodyToMono(Person.class);
Kotlin:
val result = client.get()
.uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(HttpStatus::is4xxClientError) { ... }
.onStatus(HttpStatus::is5xxServerError) { ... }
.awaitBody<Person>()
onStatus๊ฐ ์ฌ์ฉ๋๋ ๊ฒฝ์ฐ, ์๋ต์ ๋ด์ฉ(body๊ฐ)์ด ์์ ๊ฒ์ผ๋ก ์์๋๋ฉด onStatus ์ฝ๋ฐฑ์์ ์ด๋ฅผ ์๋นํด์ผ ํ๋ค.
๊ทธ๋ ์ง ์์ผ๋ฉด ๋ฆฌ์์ค ๋ฐํ์ ์ํด์ ์๋ต ๋ด์ฉ(body๊ฐ)์ด ์๋์ผ๋ก ๋น์์ง๋ค.
๋ชฉ์ฐจ ๊ฐ์ด๋