Tabnine Logo
WebClient
ClientResponse
Code IndexAdd Tabnine to your IDE (free)

How to use
WebClient
in
org.springframework.web.reactive.function.client

Reactive rest calls using spring rest template

origin: codecentric/spring-boot-admin

@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);
}
origin: spring-cloud/spring-cloud-gateway

@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));
}
origin: spring-projects/spring-security

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()) {
origin: spring-projects/spring-framework

@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();
}
origin: spring-projects/spring-data-elasticsearch

@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))));
}
origin: LearningByExample/reactive-ms-example

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)));
}
origin: srpraneeth/spring5-reactive

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;
}
origin: spring-cloud/spring-cloud-commons

@Test
public void testNoHostName() {
  ClientResponse clientResponse = WebClient.builder()
      .baseUrl("http:///foobar")
      .filter(lbFunction)
      .build()
      .get().exchange().block();
  assertThat(clientResponse.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
}
origin: emac/spring5-features-demo

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);
origin: spring-projects/spring-framework

@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();
}
origin: line/armeria

@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));
}
origin: spring-projects/spring-framework

@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();
}
origin: spring-cloud/spring-cloud-gateway

@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);
}
origin: spring-projects/spring-framework-issues

@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");
}
origin: network.quant/overledger-sdk-ethereum

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))
origin: spring-cloud/spring-cloud-gateway

@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());
}
origin: spring-cloud/spring-cloud-gateway

@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();
}
origin: spring-projects/spring-framework

@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();
}
origin: srpraneeth/spring5-reactive

@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));
}
origin: wangguobo/demo-spring-webflux-api-gateway

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));
org.springframework.web.reactive.function.clientWebClient

Javadoc

Non-blocking, reactive client to perform HTTP requests, exposing a fluent, reactive API over underlying HTTP client libraries such as Reactor Netty.

Use static factory methods #create() or #create(String), or WebClient#builder() to prepare an instance.

For examples with a response body see:

  • RequestHeadersSpec#retrieve()
  • RequestHeadersSpec#exchange()

For examples with a request body see:

  • RequestBodySpec#body(Publisher,Class)
  • RequestBodySpec#syncBody(Object)
  • RequestBodySpec#body(BodyInserter)

Most used methods

  • get
  • builder
    Return a builder for a WebClient.
  • create
    Create a new instance of WebClient with the given connector. This method uses WebClientStrategies#wi
  • post
  • method
  • mutate
  • delete
  • options
    Start building an HTTP OPTIONS request.
  • filter
    Filters this client with the given ExchangeFilterFunction, resulting in a filtered WebClient.
  • head
    Start building an HTTP HEAD request.

Popular in Java

  • Reading from database using SQL prepared statement
  • runOnUiThread (Activity)
  • getContentResolver (Context)
  • onRequestPermissionsResult (Fragment)
  • EOFException (java.io)
    Thrown when a program encounters the end of a file or stream during an input operation.
  • String (java.lang)
  • Format (java.text)
    The base class for all formats. This is an abstract base class which specifies the protocol for clas
  • Handler (java.util.logging)
    A Handler object accepts a logging request and exports the desired messages to a target, for example
  • JFileChooser (javax.swing)
  • JPanel (javax.swing)
  • CodeWhisperer alternatives
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now