@Override public Mono<Endpoints> detectEndpoints(Instance instance) { Registration registration = instance.getRegistration(); String managementUrl = registration.getManagementUrl(); if (managementUrl == null || Objects.equals(registration.getServiceUrl(), managementUrl)) { return Mono.empty(); } return instanceWebClient.instance(instance) .get() .uri(managementUrl) .exchange() .flatMap(response -> { if (response.statusCode().is2xxSuccessful() && response.headers() .contentType() .map(actuatorMediaType::isCompatibleWith) .orElse(false)) { return response.bodyToMono(Response.class); } else { return response.bodyToMono(Void.class).then(Mono.empty()); } }) .flatMap(this::convert); }
@Test public void sseAsString() { Flux<String> result = this.webClient.get() .uri("/string") .accept(TEXT_EVENT_STREAM) .exchange() .flatMapMany(response -> response.bodyToFlux(String.class)); StepVerifier.create(result) .expectNext("foo 0") .expectNext("foo 1") .thenCancel() .verify(Duration.ofSeconds(5L)); }
BodyInserters.FormInserter<String> body = body(authorizationGrantRequest); return this.webClient.post() .uri(tokenUri) .accept(MediaType.APPLICATION_JSON) .exchange() .flatMap(response ->{ if (!response.statusCode().is2xxSuccessful()){ throw WebClientResponseException.create(response.rawStatusCode(), "Cannot get token, expected 2xx HTTP Status code", null, ); return response.body(oauth2AccessTokenResponse()); }) .map(response -> { if (response.getAccessToken().getScopes().isEmpty()) {
@Test public void value() { Mono<Msg> result = this.webClient.get() .uri("/message") .exchange() .doOnNext(response -> { Assert.assertFalse(response.headers().contentType().get().getParameters().containsKey("delimited")); Assert.assertEquals("sample.proto", response.headers().header("X-Protobuf-Schema").get(0)); Assert.assertEquals("Msg", response.headers().header("X-Protobuf-Message").get(0)); }) .flatMap(response -> response.bodyToMono(Msg.class)); StepVerifier.create(result) .expectNext(TEST_MSG) .verifyComplete(); }
@Override public Mono<ClusterInformation> clusterInfo() { return createWebClient(endpoint) // .head().uri("/").exchange() // .flatMap(it -> { if (it.statusCode().isError()) { state = ElasticsearchHost.offline(endpoint); } else { state = ElasticsearchHost.online(endpoint); } return Mono.just(state); }).onErrorResume(throwable -> { state = ElasticsearchHost.offline(endpoint); clientProvider.getErrorListener().accept(throwable); return Mono.just(state); }) // .flatMap(it -> Mono.just(new ClusterInformation(Collections.singleton(it)))); }
Mono<GeoTimesResponse> get(final Mono<String> monoUrl) { return monoUrl.flatMap(url -> webClient .get() .uri(url) .accept(MediaType.APPLICATION_JSON) .exchange() .flatMap(clientResponse -> clientResponse.bodyToMono(GeoTimesResponse.class))); }
public static void main(String[] args) { // ClientResponse response = WebClient.create("http://localhost:9000").get().uri("/api/user") .accept(MediaType.APPLICATION_JSON).exchange().block(); assert response.statusCode().value() == 200; List<User> users = response.bodyToFlux(User.class).collectList().block(); assert users.size() == 2; assert users.iterator().next().getUser().equals("User1"); // User user = WebClient.create("http://localhost:9000").get().uri("/api/user/1") .accept(MediaType.APPLICATION_JSON).exchange().flatMap(resp -> resp.bodyToMono(User.class)).block(); assert user.getId() == 1; assert user.getUser().equals("User1"); response = WebClient.create("http://localhost:9000").get().uri("/api/user/10") .accept(MediaType.APPLICATION_JSON).exchange().block(); assert response.statusCode().value() == 404; }
@Test public void testNoHostName() { ClientResponse clientResponse = WebClient.builder() .baseUrl("http:///foobar") .filter(lbFunction) .build() .get().exchange().block(); assertThat(clientResponse.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST); }
WebClient webClient = WebClient.create("http://localhost:9090"); Restaurant[] restaurants = IntStream.range(0, 100) .mapToObj(String::valueOf) webClient.post().uri("/reactive/restaurants") .accept(MediaType.APPLICATION_JSON_UTF8) .syncBody(restaurants) .exchange() .flatMapMany(resp -> resp.bodyToFlux(Restaurant.class)) .log() webClient.get() .uri("/reactive/restaurants/{id}", r1.getId()) .accept(MediaType.APPLICATION_JSON_UTF8) .exchange() .flatMap(resp -> resp.bodyToMono(Restaurant.class)) .log() .subscribe(r2 -> result.set(r2.equals(r1)), e -> latch.countDown(), latch::countDown);
@Test public void fixedLocale() { Mono<ClientResponse> result = webClient .get() .uri("http://localhost:" + this.port + "/") .exchange(); StepVerifier .create(result) .consumeNextWith(response -> { assertEquals(HttpStatus.OK, response.statusCode()); assertEquals(Locale.GERMANY, response.headers().asHttpHeaders().getContentLanguage()); }) .verifyComplete(); }
@Test public void getConflict() { final Mono<ClientResponse> response = webClient.get() .uri(uri("/conflict")) .exchange(); StepVerifier.create(response) .assertNext(r -> assertThat(r.statusCode()).isEqualTo(HttpStatus.CONFLICT)) .expectComplete() .verify(Duration.ofSeconds(10)); }
@Test public void values() { Flux<Msg> result = this.webClient.get() .uri("/messages") .exchange() .doOnNext(response -> { Assert.assertEquals("true", response.headers().contentType().get().getParameters().get("delimited")); Assert.assertEquals("sample.proto", response.headers().header("X-Protobuf-Schema").get(0)); Assert.assertEquals("Msg", response.headers().header("X-Protobuf-Message").get(0)); }) .flatMapMany(response -> response.bodyToFlux(Msg.class)); StepVerifier.create(result) .expectNext(TEST_MSG) .expectNext(TEST_MSG) .expectNext(TEST_MSG) .verifyComplete(); }
@Test public void nonStandardHeadersInResponse() { URI uri = UriComponentsBuilder .fromUriString(this.baseUri + "/get-image") .build(true) .toUri(); String contentType = WebClient.builder() .baseUrl(baseUri) .build() .get() .uri(uri) .exchange() .map(clientResponse -> clientResponse.headers().asHttpHeaders().getFirst(HttpHeaders.CONTENT_TYPE)) .block(); assertEquals(CONTENT_TYPE_IMAGE, contentType); }
@Test public void should_translate_error_to_polish() { // when ClientResponse response = WebClient.create().post() .uri("http://localhost:" + port + "/validate") .header("Accept-Language", "pl-PL") .body(Mono.just(new TestBody()), TestBody.class) .exchange() .block(); // then Map body = response.bodyToMono(Map.class).block(); String message = (String) ((Map) (((List) body.get("errors")).get(0))).get("defaultMessage"); Assertions.assertThat(message).isEqualTo("musi być podane"); }
String address = Credentials.create(ethereumAccount.getEcKeyPair()).getAddress(); this.webClient .post() .uri(this.url, address, new BigDecimal("1000000000000000000")) .retrieve() .onStatus(HttpStatus::is4xxClientError, clientResponse -> clientResponse .bodyToMono(ByteArrayResource.class) .map(ByteArrayResource::getByteArray) .map(String::new) .bodyToMono(ByteArrayResource.class) .map(ByteArrayResource::getByteArray) .map(String::new) .map(ClientResponseException::new) .onStatus(HttpStatus::is3xxRedirection, clientResponse -> Mono.error(new RedirectException(clientResponse.headers().header("Location").get(0)))) .bodyToMono(String.class) .doOnSuccess(faucetResponseDto -> ethereumAccount.setNonce(null != nonce?nonce:BigInteger.ZERO))
@Test public void testPreFlightCorsRequest() { ClientResponse clientResponse = webClient.options().uri("/abc/123/function") .header("Origin", "domain.com") .header("Access-Control-Request-Method", "GET").exchange().block(); HttpHeaders asHttpHeaders = clientResponse.headers().asHttpHeaders(); Mono<String> bodyToMono = clientResponse.bodyToMono(String.class); // pre-flight request shouldn't return the response body assertNull(bodyToMono.block()); assertEquals( "Missing header value in response: " + HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*", asHttpHeaders.getAccessControlAllowOrigin()); assertEquals( "Missing header value in response: " + HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, Arrays.asList(new HttpMethod[] { HttpMethod.GET }), asHttpHeaders.getAccessControlAllowMethods()); assertEquals("Pre Flight call failed.", HttpStatus.OK, clientResponse.statusCode()); }
@Test public void webCallShouldTriggerWebSessionSaveAction() { when(mockWebSession.getAttributes()).thenReturn(new HashMap<>()); when(mockWebSession.save()).thenReturn(Mono.empty()); Mono<Map> result = webClient.get() .uri("/get") .exchange() .flatMap(response -> response.body(toMono(Map.class))); StepVerifier.create(result) .consumeNextWith(response -> {/* Don't care about data, just need to catch signal */}) .expectComplete() .verify(Duration.ofMinutes(10)); verify(mockWebSession).save(); }
@Test public void requestPart() { Mono<ClientResponse> result = webClient .post() .uri("/requestPart") .syncBody(generateBody()) .exchange(); StepVerifier .create(result) .consumeNextWith(response -> assertEquals(HttpStatus.OK, response.statusCode())) .verifyComplete(); }
@GetMapping("/user/{id}") public Mono<ServerResponse> handleGetUserById(@PathVariable String id) { return WebClient.create("http://localhost:9000").get().uri("/api/user/" + id) .accept(MediaType.APPLICATION_JSON).exchange().flatMap(resp -> ServerResponse.ok().body(resp.bodyToMono(User.class), User.class)); }
String path = frontEndReq.getPath().pathWithinApplication().value(); HttpMethod httpMethod = frontEndReq.getMethod(); RequestBodySpec reqBodySpec = webClient.method(httpMethod). uri(backendServiceUrlPrefix.concat(path)). headers(httpHeaders -> frontEndResp.setStatusCode(backendResponse.statusCode()); frontEndResp.getHeaders().putAll(backendResponse.headers().asHttpHeaders()); return frontEndResp.writeWith(backendResponse.bodyToFlux(DataBuffer.class));