org.springframework.web.reactive.function.client.WebClient类的使用及代码示例

x33g5p2x  于2022-02-03 转载在 其他  
字(10.9k)|赞(0)|评价(0)|浏览(1270)

本文整理了Java中org.springframework.web.reactive.function.client.WebClient类的一些代码示例,展示了WebClient类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。WebClient类的具体详情如下:
包路径:org.springframework.web.reactive.function.client.WebClient
类名称:WebClient

WebClient介绍

[英]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)
    [中]非阻塞、反应式客户端执行HTTP请求,通过底层HTTP客户端库(如Reactor Netty)公开流畅、反应式API。
    使用静态工厂方法#create()或#create(String)或WebClient#builder()来准备实例。
    有关响应主体的示例,请参见:
    *RequestHeadersSpec#retrieve()
    *RequestHeadersSpec#exchange()
    有关请求主体的示例,请参见:
    *RequestBodySpec#body(出版商,类别)
    *RequestBodySpec#syncBody(对象)
    *请求车身规格#车身(车身插入器)

代码示例

代码示例来源:origin: spring-projects/spring-framework

@Test
public void uriBuilderWithPathOverride() {
  this.builder.build().get()
      .uri(builder -> builder.replacePath("/path").build())
      .exchange();
  ClientRequest request = verifyAndGetRequest();
  assertEquals("/path", request.url().toString());
  verifyNoMoreInteractions(this.exchangeFunction);
}

代码示例来源:origin: spring-projects/spring-framework

private DefaultWebTestClientBuilder(@Nullable WebClient.Builder webClientBuilder,
    @Nullable WebHttpHandlerBuilder httpHandlerBuilder, @Nullable ClientHttpConnector connector,
    @Nullable Duration responseTimeout) {
  Assert.isTrue(httpHandlerBuilder != null || connector != null,
      "Either WebHttpHandlerBuilder or ClientHttpConnector must be provided");
  this.webClientBuilder = (webClientBuilder != null ? webClientBuilder : WebClient.builder());
  this.httpHandlerBuilder = (httpHandlerBuilder != null ? httpHandlerBuilder.clone() : null);
  this.connector = connector;
  this.responseTimeout = responseTimeout;
}

代码示例来源:origin: spring-projects/spring-framework

@Before
public void setup() throws Exception {
  super.setup();
  this.webClient = WebClient.create("http://localhost:" + this.port);
}

代码示例来源:origin: spring-projects/spring-framework

@Test  // SPR-15782
public void shouldFailWithRelativeUrls() {
  String uri = "/api/v4/groups/1";
  Mono<ClientResponse> responseMono = WebClient.builder().build().get().uri(uri).exchange();
  StepVerifier.create(responseMono)
      .expectErrorMessage("URI is not absolute: " + uri)
      .verify(Duration.ofSeconds(5));
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void setWebClientCustomThenCustomClientIsUsed() {
  WebClient customClient = mock(WebClient.class);
  when(customClient.post()).thenReturn(WebClient.builder().build().post());
  this.client.setWebClient(customClient);
  ClientRegistration registration = this.clientRegistration.build();
  enqueueJson("{\n"
      + "  \"access_token\":\"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3\",\n"
      + "  \"token_type\":\"bearer\",\n"
      + "  \"expires_in\":3600,\n"
      + "  \"refresh_token\":\"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk\"\n"
      + "}");
  OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(registration);
  OAuth2AccessTokenResponse response = this.client.getTokenResponse(request).block();
  verify(customClient, atLeastOnce()).post();
}

代码示例来源:origin: spring-projects/spring-framework-issues

public static void main(String[] args) {
    WebClient client = WebClient.create("http://localhost:8080");
    Flux<WebfluxApplication.Pojo> pojoFlux = client.get().uri("/dummy").retrieve().bodyToFlux(WebfluxApplication.Pojo.class);
    pojoFlux.count().block();
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Test(expected = IllegalArgumentException.class)
public void bodyObjectPublisher() {
  Mono<Void> mono = Mono.empty();
  WebClient client = this.builder.build();
  client.post().uri("http://example.com").syncBody(mono);
}

代码示例来源:origin: rstoyanchev/demo-reactive-spring

public static void main(String[] args) {
  WebClient client = WebClient.create("http://localhost:8081");
  LocationGenerator gen = new LocationGenerator(40.740900, -73.988000);
  Flux<Car> cars = Flux.interval(Duration.ofSeconds(2)).map(i -> new Car(i + 200, gen.location()));
  client.post()
      .uri("/cars")
      .contentType(MediaType.APPLICATION_STREAM_JSON)
      .body(cars, Car.class)
      .retrieve()
      .bodyToMono(Void.class)
      .block();
}

代码示例来源:origin: spring-projects/spring-security

WebClient.RequestHeadersSpec<?> requestHeadersSpec;
if (AuthenticationMethod.FORM.equals(authenticationMethod)) {
  requestHeadersSpec = this.webClient.post()
      .uri(userInfoUri)
      .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
      .syncBody("access_token=" + userRequest.getAccessToken().getTokenValue());
} else {
  requestHeadersSpec = this.webClient.get()
      .uri(userInfoUri)
      .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)

代码示例来源:origin: spring-projects/spring-framework

WebClient filteredClient = this.webClient.mutate().filter(filter).build();
    .setHeader("Content-Type", "text/plain").setBody("Hello Spring!"));
Mono<String> result = filteredClient.get()
    .uri("/greeting?name=Spring")
    .retrieve()
    .setBody("Hello Spring!"));
result = filteredClient.get()
    .uri("/greeting?name=Spring")
    .retrieve().bodyToMono(String.class);

代码示例来源:origin: spring-projects/spring-framework

private RequestBodyUriSpec methodInternal(HttpMethod method) {
  return new DefaultRequestBodyUriSpec(this.webClient.method(method));
}

代码示例来源:origin: spring-projects/spring-framework

WebClient.Builder builder = WebClient.builder()
    .filter((request, next) -> next.exchange(request))
    .defaultHeader("foo", "bar")
    .build();
WebClient client1a = client1.mutate()
    .filter((request, next) -> next.exchange(request))
    .defaultHeader("baz", "qux")
WebClient.Builder builder1 = client1.mutate();
builder1.filters(filters -> assertEquals(1, filters.size()));
builder1.defaultHeaders(headers -> assertEquals(1, headers.size()));
builder1.defaultCookies(cookies -> assertEquals(1, cookies.size()));
WebClient.Builder builder2 = client2.mutate();
builder2.filters(filters -> assertEquals(2, filters.size()));
builder2.defaultHeaders(headers -> assertEquals(2, headers.size()));
builder2.defaultCookies(cookies -> assertEquals(2, cookies.size()));
WebClient.Builder builder1a = client1a.mutate();
builder1a.filters(filters -> assertEquals(2, filters.size()));
builder1a.defaultHeaders(headers -> assertEquals(2, headers.size()));

代码示例来源:origin: codecentric/spring-boot-admin

public WebClient instance(Instance instance) {
  return webClient.mutate()
          .filters(filters -> filters.add(0, InstanceExchangeFilterFunctions.setInstance(instance)))
          .build();
}

代码示例来源:origin: com.holon-platform.reactor/holon-reactor-spring

WebClient.Builder builder = getClient().mutate();
final RequestBodySpec spec = client.method(requestMethod).uri(ub -> {

代码示例来源: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: 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

@Test  // SPR-16246
public void shouldSendLargeTextFile() throws IOException {
  prepareResponse(response -> {});
  Resource resource = new ClassPathResource("largeTextFile.txt", getClass());
  byte[] expected = Files.readAllBytes(resource.getFile().toPath());
  Flux<DataBuffer> body = DataBufferUtils.read(resource, new DefaultDataBufferFactory(), 4096);
  this.webClient.post()
      .uri("/")
      .body(body, DataBuffer.class)
      .retrieve()
      .bodyToMono(Void.class)
      .block(Duration.ofSeconds(5));
  expectRequest(request -> {
    ByteArrayOutputStream actual = new ByteArrayOutputStream();
    try {
      request.getBody().copyTo(actual);
    }
    catch (IOException ex) {
      throw new IllegalStateException(ex);
    }
    assertEquals(expected.length, actual.size());
    assertEquals(hash(expected), hash(actual.toByteArray()));
  });
}

代码示例来源:origin: rayokota/kafka-graphs

private Flux<GraphAlgorithmId> proxyConfigure(Set<String> groupMembers, String appId, GraphAlgorithmCreateRequest input) {
  Flux<GraphAlgorithmId> flux = Flux.fromIterable(groupMembers)
    .filter(s -> !s.equals(getHostAndPort()))
    .flatMap(s -> {
      log.debug("proxy configure to {}", s);
      WebClient client = WebClient.create("http://" + s);
      return client.post().uri("/pregel")
        .accept(MediaType.APPLICATION_JSON)
        .header(X_KGRAPH_APPID, appId)
        .body(Mono.just(input), GraphAlgorithmCreateRequest.class)
        .retrieve()
        .bodyToMono(GraphAlgorithmId.class);
    });
  return flux;
}

代码示例来源:origin: Dromara/soul

private Mono<Void> doHttpInvoke() {
  if (requestDTO.getHttpMethod().equals(HttpMethodEnum.GET.getName())) {
    String uri = buildRealURL();
    if (StringUtils.isNoneBlank(requestDTO.getExtInfo())) {
      uri = uri + "?" + GSONUtils.getInstance().toGetParam(requestDTO.getExtInfo());
    }
    return WEB_CLIENT.get().uri(uri)
        .headers(httpHeaders -> {
          httpHeaders.addAll(exchange.getRequest().getHeaders());
          httpHeaders.remove(HttpHeaders.HOST);
        })
        .exchange()
        .doOnError(e -> LogUtils.error(LOGGER, e::getMessage))
        .timeout(Duration.ofMillis(timeout))
        .flatMap(this::doNext);
  } else if (requestDTO.getHttpMethod().equals(HttpMethodEnum.POST.getName())) {
    return WEB_CLIENT.post().uri(buildRealURL())
        .headers(httpHeaders -> {
          httpHeaders.addAll(exchange.getRequest().getHeaders());
          httpHeaders.remove(HttpHeaders.HOST);
        })
        .contentType(buildMediaType())
        .body(BodyInserters.fromDataBuffers(exchange.getRequest().getBody()))
        .exchange()
        .doOnError(e -> LogUtils.error(LOGGER, e::getMessage))
        .timeout(Duration.ofMillis(timeout))
        .flatMap(this::doNext);
  }
  return Mono.empty();
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void shouldApplyExchangeFilter() {
  prepareResponse(response -> response.setHeader("Content-Type", "text/plain")
      .setBody("Hello Spring!"));
  WebClient filteredClient = this.webClient.mutate()
      .filter((request, next) -> {
        ClientRequest filteredRequest =
            ClientRequest.from(request).header("foo", "bar").build();
        return next.exchange(filteredRequest);
      })
      .build();
  Mono<String> result = filteredClient.get()
      .uri("/greeting?name=Spring")
      .retrieve()
      .bodyToMono(String.class);
  StepVerifier.create(result)
      .expectNext("Hello Spring!")
      .expectComplete()
      .verify(Duration.ofSeconds(3));
  expectRequestCount(1);
  expectRequest(request -> assertEquals("bar", request.getHeader("foo")));
}

相关文章