org.springframework.web.reactive.function.client.WebClient Java Examples
The following examples show how to use
org.springframework.web.reactive.function.client.WebClient.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HelloFluxApplicationTests.java From Spring5Tutorial with GNU Lesser General Public License v3.0 | 6 votes |
@Test public void testHello() { Mono<String> userName = WebClient.create("http://localhost:8080/") .get() .uri("hello/caterpillar") .accept(MediaType.APPLICATION_JSON) .exchange() .flatMap(response -> response.bodyToMono(User.class)) .map(User::getName); StepVerifier.create(userName) .expectNext("caterpillar") .expectComplete() .verify(); }
Example #2
Source File: WebClientTransportClientFactory.java From spring-cloud-netflix with Apache License 2.0 | 6 votes |
private WebClient.Builder of(String serviceUrl) { String url = serviceUrl; WebClient.Builder builder = WebClient.builder(); try { URI serviceURI = new URI(serviceUrl); if (serviceURI.getUserInfo() != null) { String[] credentials = serviceURI.getUserInfo().split(":"); if (credentials.length == 2) { builder.filter(ExchangeFilterFunctions .basicAuthentication(credentials[0], credentials[1])); url = serviceUrl.replace(credentials[0] + ":" + credentials[1] + "@", ""); } } } catch (URISyntaxException ignore) { } return builder.baseUrl(url); }
Example #3
Source File: TraceWebClientBeanPostProcessorTest.java From spring-cloud-sleuth with Apache License 2.0 | 6 votes |
@Test void should_add_filter_only_once_to_web_client_via_builder() { TraceWebClientBeanPostProcessor processor = new TraceWebClientBeanPostProcessor( this.springContext); WebClient.Builder builder = WebClient.builder(); builder = (WebClient.Builder) processor.postProcessAfterInitialization(builder, "foo"); builder = (WebClient.Builder) processor.postProcessAfterInitialization(builder, "foo"); builder.build().mutate().filters(filters -> { BDDAssertions.then(filters).hasSize(1); BDDAssertions.then(filters.get(0)) .isInstanceOf(TraceExchangeFilterFunction.class); }); }
Example #4
Source File: SpringWebFluxUnitTest.java From tutorials with MIT License | 6 votes |
@Test public void givenReactiveClient_whenRequested_shouldReturnResponse() throws Exception { HttpClient httpClient = new HttpClient(); httpClient.start(); ClientHttpConnector clientConnector = new JettyClientHttpConnector(httpClient); WebClient client = WebClient.builder() .clientConnector(clientConnector) .build(); String responseContent = client.post() .uri(uri()) .contentType(MediaType.TEXT_PLAIN) .body(BodyInserters.fromPublisher(Mono.just(CONTENT), String.class)) .retrieve() .bodyToMono(String.class) .block(); Assert.assertNotNull(responseContent); Assert.assertEquals(CONTENT, responseContent); }
Example #5
Source File: AppSyncClientHelper.java From tutorials with MIT License | 5 votes |
public static WebClient.ResponseSpec getResponseBodySpec(Map<String, Object> requestBody) { return WebClient .builder() .baseUrl(apiUrl) .defaultHeader(API_KEY_HEADER, apiKey) .defaultHeader("Content-Type", "application/json") .build() .method(HttpMethod.POST) .uri("/graphql") .body(BodyInserters.fromValue(requestBody)) .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .acceptCharset(StandardCharsets.UTF_8) .retrieve(); }
Example #6
Source File: ReactiveVaultTemplate.java From spring-vault with Apache License 2.0 | 5 votes |
@Override public <V, T extends Publisher<V>> T doWithVault(Function<WebClient, ? extends T> clientCallback) throws VaultException, WebClientException { Assert.notNull(clientCallback, "Client callback must not be null"); try { return (T) clientCallback.apply(this.statelessClient); } catch (HttpStatusCodeException e) { throw VaultResponses.buildException(e); } }
Example #7
Source File: BookingService.java From Spring-5.0-By-Example with MIT License | 5 votes |
public BookingService(WebClient webClient, DiscoveryService discoveryService, @Value("${bookings.service}") String bookingsService, TokenService tokenService, @Qualifier("bookingsCredentials") Credentials credentials) { this.webClient = webClient; this.discoveryService = discoveryService; this.bookingsService = bookingsService; this.tokenService = tokenService; this.credentials = credentials; }
Example #8
Source File: HealthCheckServiceInstanceListSupplier.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
public HealthCheckServiceInstanceListSupplier(ServiceInstanceListSupplier delegate, LoadBalancerProperties.HealthCheck healthCheck, WebClient webClient) { super(delegate); this.healthCheck = healthCheck; defaultHealthCheckPath = healthCheck.getPath().getOrDefault("default", "/actuator/health"); this.webClient = webClient; aliveInstancesReplay = Flux.defer(delegate) .delaySubscription(healthCheck.getInitialDelay()) .switchMap(serviceInstances -> healthCheckFlux(serviceInstances).map( alive -> Collections.unmodifiableList(new ArrayList<>(alive)))) .replay(1).refCount(1); }
Example #9
Source File: TokenService.java From Spring-5.0-By-Example with MIT License | 5 votes |
public TokenService(WebClient webClient, @Value("${auth.service}") String authService, @Value("${auth.path}") String authServiceApiPath, DiscoveryService discoveryService) { this.webClient = webClient; this.authService = authService; this.authServiceApiPath = authServiceApiPath; this.discoveryService = discoveryService; }
Example #10
Source File: SupplierExporter.java From spring-cloud-function with Apache License 2.0 | 5 votes |
SupplierExporter(RequestBuilder requestBuilder, DestinationResolver destinationResolver, FunctionCatalog catalog, WebClient client, ExporterProperties exporterProperties) { this.requestBuilder = requestBuilder; this.destinationResolver = destinationResolver; this.catalog = catalog; this.client = client; this.debug = exporterProperties.isDebug(); this.autoStartup = exporterProperties.isAutoStartup(); this.supplier = exporterProperties.getSink().getName(); this.contentType = exporterProperties.getSink().getContentType(); }
Example #11
Source File: GithubRoutesConfig.java From spring-5-examples with MIT License | 5 votes |
@Bean RouterFunction<ServerResponse> githubRoutes(final GithubProperties props, final WebClient githubWebClient) { return route(GET("/github/props/manual"), request -> ok().body(Mono.just( singletonMap("github", singletonMap("token", props.getToken()))), Map.class)) .andRoute(GET("/github/props/**"), request -> ok().body(Mono.just(props), GithubProperties.class)) .andRoute(GET("/github/search/users/{username}"), // ?page=1&size=2 request -> ok().body(githubWebClient.get() .uri( "/search/users?q={q}&page={page}&per_page={per_page}", HashMap.of( "q", request.pathVariable("username"), "page", request.queryParam("page").orElse("0"), "per_page", request.queryParam("size").orElse("3") ).toJavaMap() ) .exchange() .subscribeOn(Schedulers.elastic()) .flatMapMany(response -> response.bodyToFlux(Map.class)), Map.class)) .andRoute(GET("/**"), request -> ok().body(Mono.just(singletonMap("result", "TODO")), Map.class)) ; }
Example #12
Source File: FilteredWebClientUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void testLoggingFilter() throws IOException { stubFor(get(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200) .withBody("done"))); try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos);) { WebClient webClient = WebClient.builder() .filter(loggingFilter(ps)) .build(); String actual = sendGetRequest(webClient); assertThat(actual).isEqualTo("done"); assertThat(baos.toString()).isEqualTo("Sending request GET " + getUrl()); } }
Example #13
Source File: PlaneService.java From Learning-Path-Spring-5-End-to-End-Programming with MIT License | 5 votes |
public PlaneService(WebClient webClient, DiscoveryService discoveryService,TokenService tokenService, @Value("${planes.service}") String planesService) { this.webClient = webClient; this.discoveryService = discoveryService; this.planesService = planesService; this.tokenService = tokenService; }
Example #14
Source File: WebClientConfiguration.java From blog-tutorials with MIT License | 5 votes |
@Bean public WebClient webClient(WebClient.Builder webClientBuilder) { TcpClient tcpClient = TcpClient.create() .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2_000) .doOnConnected(connection -> connection.addHandlerLast(new ReadTimeoutHandler(2)) .addHandlerLast(new WriteTimeoutHandler(2))); return webClientBuilder .defaultHeader(HttpHeaders.USER_AGENT, "SAMPLE_APP") .clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient))) .build(); }
Example #15
Source File: BookingService.java From Learning-Path-Spring-5-End-to-End-Programming with MIT License | 5 votes |
public BookingService(WebClient webClient, DiscoveryService discoveryService,TokenService tokenService, @Value("${bookings.service}") String bookingsService,@Qualifier("bookingsCredentials") Credentials bookingsCredentials) { this.webClient = webClient; this.discoveryService = discoveryService; this.bookingsService = bookingsService; this.tokenService = tokenService; this.bookingsCredentials = bookingsCredentials; }
Example #16
Source File: ProductCompositeIntegration.java From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License | 5 votes |
@Autowired public ProductCompositeIntegration( WebClient.Builder webClientBuilder, ObjectMapper mapper, MessageSources messageSources ) { this.webClientBuilder = webClientBuilder; this.mapper = mapper; this.messageSources = messageSources; }
Example #17
Source File: TokenService.java From Learning-Path-Spring-5-End-to-End-Programming with MIT License | 5 votes |
public TokenService(WebClient webClient, @Value("${auth.service}") String authService, @Value("${auth.path}") String authServiceApiPath, DiscoveryService discoveryService) { this.webClient = webClient; this.authService = authService; this.authServiceApiPath = authServiceApiPath; this.discoveryService = discoveryService; }
Example #18
Source File: ReactiveBackendWebClientConfig.java From spring-5-examples with MIT License | 5 votes |
@Bean public WebClient webClient(final ReactiveBackendConfig backend) { return WebClient.builder() .baseUrl(backend.getBaseUrl()) .filter(ExchangeFilterFunctions.basicAuthentication(backend.getCredentials().getUsername(), backend.getCredentials().getPassword())) .build(); }
Example #19
Source File: ReactorLoadBalancerExchangeFilterFunctionTests.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
@Test void correctResponseReturnedForExistingHostAndInstancePresent() { ClientResponse clientResponse = WebClient.builder().baseUrl("http://testservice") .filter(this.loadBalancerFunction).build().get().uri("/hello").exchange() .block(); then(clientResponse.statusCode()).isEqualTo(HttpStatus.OK); then(clientResponse.bodyToMono(String.class).block()).isEqualTo("Hello World"); }
Example #20
Source File: NonStandardHeadersInResponseTests.java From spring-cloud-gateway with Apache License 2.0 | 5 votes |
@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(); assertThat(contentType).isEqualTo(CONTENT_TYPE_IMAGE); }
Example #21
Source File: ProductCompositeIntegration.java From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License | 5 votes |
@Autowired public ProductCompositeIntegration( WebClient.Builder webClientBuilder, ObjectMapper mapper, MessageSources messageSources, @Value("${app.product-service.timeoutSec}") int productServiceTimeoutSec ) { this.webClientBuilder = webClientBuilder; this.mapper = mapper; this.messageSources = messageSources; this.productServiceTimeoutSec = productServiceTimeoutSec; }
Example #22
Source File: ReactiveCredHubTemplate.java From spring-credhub with Apache License 2.0 | 5 votes |
/** * Allow interaction with the configured {@link WebClient} not provided by other * methods. * @param callback wrapper for the callback method * @param <T> the credential implementation type * @return the return value from the callback method */ @Override public <V, T extends Publisher<V>> T doWithWebClient(Function<WebClient, ? extends T> callback) { Assert.notNull(callback, "callback must not be null"); try { return callback.apply(this.webClient); } catch (HttpStatusCodeException ex) { throw new CredHubException(ex); } }
Example #23
Source File: WebClientConfig.java From oauth2-protocol-patterns with Apache License 2.0 | 5 votes |
@Bean WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) { ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); return WebClient.builder() .apply(oauth2Client.oauth2Configuration()) .build(); }
Example #24
Source File: PrepareVault.java From spring-vault with Apache License 2.0 | 5 votes |
/** * Create a new {@link PrepareVault} object. * @param webClient must not be {@literal null}. * @param restTemplate must not be {@literal null}. * @param vaultOperations must not be {@literal null}. */ public PrepareVault(WebClient webClient, RestTemplate restTemplate, VaultOperations vaultOperations) { this.webClient = webClient; this.restTemplate = restTemplate; this.vaultOperations = vaultOperations; this.adminOperations = vaultOperations.opsForSys(); }
Example #25
Source File: SecurityConfig.java From spring-security-samples with MIT License | 5 votes |
@Bean WebClient tokenAugmentingWebClient(final ReactiveClientRegistrationRepository clientRegistrationRepository, final ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { return WebClient.builder() .filter(new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrationRepository, authorizedClientRepository)) .build(); }
Example #26
Source File: ClientCertificateAuthenticationOperatorIntegrationTests.java From spring-vault with Apache License 2.0 | 5 votes |
@Test void shouldSelectKey() { WebClient webClient = TestWebClientFactory.create( prepareCertAuthenticationMethod(SslConfiguration.KeyConfiguration.of("changeit".toCharArray(), "1"))); AuthenticationStepsOperator operator = new AuthenticationStepsOperator( ClientCertificateAuthentication.createAuthenticationSteps(), webClient); operator.getVaultToken() // .as(StepVerifier::create) // .expectNextCount(1) // .verifyComplete(); }
Example #27
Source File: CustomerControllerTest.java From coditori with Apache License 2.0 | 5 votes |
@Test public void test2_add_customer_done() { WebClient webClient = WebClient.create("http://localhost:" + port); Customer customer = webClient.post().uri("/customers") .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromObject(newCustomer)) .retrieve() .bodyToMono(Customer.class) .block(); id = customer.getId(); System.out.println("id " + id); assertThat(customer.getName(), is(newCustomer.getName())); }
Example #28
Source File: ReactiveVaultTemplate.java From spring-vault with Apache License 2.0 | 5 votes |
/** * Create a new {@link ReactiveVaultTemplate} with a {@link VaultEndpointProvider} and * {@link ClientHttpConnector}. This constructor does not use a * {@link VaultTokenSupplier}. It is intended for usage with Vault Agent to inherit * Vault Agent's authentication without using the {@link VaultHttpHeaders#VAULT_TOKEN * authentication token header}. * @param endpointProvider must not be {@literal null}. * @param connector must not be {@literal null}. * @since 2.2.1 */ public ReactiveVaultTemplate(VaultEndpointProvider endpointProvider, ClientHttpConnector connector) { Assert.notNull(endpointProvider, "VaultEndpointProvider must not be null"); Assert.notNull(connector, "ClientHttpConnector must not be null"); WebClient webClient = doCreateWebClient(endpointProvider, connector); this.vaultTokenSupplier = NoTokenSupplier.INSTANCE; this.statelessClient = webClient; this.sessionClient = webClient; }
Example #29
Source File: ReactiveReceiverApplicationTest.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Test public void testSample() throws UnsupportedEncodingException { String messagePostingUrl = UriComponentsBuilder.newInstance() .scheme("http") .host("localhost") .port(this.port) .path("/postMessage") .toUriString(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("message", "reactive test msg"); map.add("count", "2"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); testRestTemplate.postForObject(messagePostingUrl, request, String.class); List<String> streamedMessages = WebClient.create("http://localhost:" + this.port).get() .uri("/getmessages") .accept(MediaType.TEXT_EVENT_STREAM) .retrieve() .bodyToFlux(String.class) .limitRequest(2) .collectList().block(Duration.ofSeconds(10)); assertThat(streamedMessages).containsExactlyInAnyOrder("reactive test msg 0", "reactive test msg 1"); }
Example #30
Source File: FilteredWebClientUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenUrlModifyingFilter_thenPathModified() { stubFor(get(urlPathEqualTo(PATH + "/1.0")).willReturn(aResponse().withStatus(200) .withBody("done"))); WebClient webClient = WebClient.builder() .filter(urlModifyingFilter("1.0")) .build(); String actual = sendGetRequest(webClient); assertThat(actual).isEqualTo("done"); verify(getRequestedFor(urlPathEqualTo(PATH + "/1.0"))); }