@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())); }); }
requestBodySpec.body(Mono.fromSupplier(body::get), String.class); } else { ClientLogger.logRequest(logId, request.getMethod().toUpperCase(), request.getEndpoint(), request.getParameters());
@Test public void multipartFormDataWorks() { ClassPathResource img = new ClassPathResource("1x1.png"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_PNG); HttpEntity<ClassPathResource> entity = new HttpEntity<>(img, headers); MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(); parts.add("imgpart", entity); Mono<Map> result = webClient.post() .uri("/post") .contentType(MediaType.MULTIPART_FORM_DATA) .body(BodyInserters.fromMultipartData(parts)) .exchange() .flatMap(response -> response.body(toMono(Map.class))); StepVerifier.create(result) .consumeNextWith(map -> { Map<String, Object> files = getMap(map, "files"); assertThat(files).containsKey("imgpart"); String file = (String) files.get("imgpart"); assertThat(file).startsWith("data:").contains(";base64,"); }) .expectComplete() .verify(DURATION); }
@Override public Publisher<Object> executeRequest(ReactiveHttpRequest request) { ReactiveHttpRequest requestPreprocessed = requestInterceptor.apply(request); logger.logRequest(methodTag, requestPreprocessed); long start = System.currentTimeMillis(); WebClient.ResponseSpec response = webClient.method(requestPreprocessed.method()) .uri(requestPreprocessed.uri()) .headers(httpHeaders -> setUpHeaders(requestPreprocessed, httpHeaders)) .body(provideBody(requestPreprocessed)) .retrieve() .onStatus(httpStatus -> true, resp -> handleResponseStatus(metadata.configKey(), resp, start)); if (returnPublisherType == Mono.class) { return response.bodyToMono(returnActualType).map(responseLogger(start)); } else { return response.bodyToFlux(returnActualType).map(responseLogger(start)); } }
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; }
@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"); }
@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"); }
private Flux<GraphAlgorithmStatus> proxyRun(Set<String> groupMembers, String appId, GraphAlgorithmRunRequest input) { Flux<GraphAlgorithmStatus> flux = Flux.fromIterable(groupMembers) .filter(s -> !s.equals(getHostAndPort())) .flatMap(s -> { log.debug("proxy run to {}", s); WebClient client = WebClient.create("http://" + s); return client.post().uri("/pregel/" + appId) .accept(MediaType.APPLICATION_JSON) .header(X_KGRAPH_APPID, appId) .body(Mono.just(input), GraphAlgorithmRunRequest.class) .retrieve() .bodyToMono(GraphAlgorithmStatus.class); }); return flux; }
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(); }
@Override public Mono<ReactiveHttpResponse> executeRequest(ReactiveHttpRequest request) { return webClient.method(HttpMethod.valueOf(request.method())) .uri(request.uri()) .headers(httpHeaders -> setUpHeaders(request, httpHeaders)) .body(provideBody(request)) .exchange() .onErrorMap(ex -> ex instanceof io.netty.handler.timeout.ReadTimeoutException, ReadTimeoutException::new) .map(response -> new WebReactiveHttpResponse(response, returnPublisherType, returnActualType)); }
private Mono<ClientResponse> post(URI uri, String destination, Object value) { Mono<ClientResponse> result = client.post().uri(uri) .headers(headers -> headers(headers, destination, value)) .body(BodyInserters.fromObject(value)).exchange(); if (this.debug) { result = result.log(); } return result; }
private Mono<ClientResponse> post(URI uri, String destination, Object value) { Mono<ClientResponse> result = client.post().uri(uri) .headers(headers -> headers(headers, destination, value)) .body(BodyInserters.fromObject(value)).exchange(); if (this.debug) { result = result.log(); } return result; }
requestSpec.body(BodyInserters.fromObject(httpRequest.getBody())); // NOSONAR protected with hasBody()
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(); }
headersSpec = bodySpec.body(BodyInserters.fromDataBuffers(request.getBody())); } else { headersSpec = bodySpec;
private Mono<ResponseEntity<T>> exchange(RequestEntity<?> requestEntity) { Type type = this.responseType; RequestBodySpec builder = rest.method(requestEntity.getMethod()) .uri(requestEntity.getUrl()) .headers(headers -> addHeaders(headers, requestEntity.getHeaders())); Mono<ClientResponse> result; if (requestEntity.getBody() instanceof Publisher) { @SuppressWarnings("unchecked") Publisher<Object> publisher = (Publisher<Object>) requestEntity.getBody(); result = builder.body(publisher, Object.class).exchange(); } else if (requestEntity.getBody() != null) { result = builder.body(BodyInserters.fromObject(requestEntity.getBody())) .exchange(); } else { if (hasBody) { result = builder.headers( headers -> addHeaders(headers, exchange.getRequest().getHeaders())) .body(exchange.getRequest().getBody(), DataBuffer.class) .exchange(); } else { result = builder.headers( headers -> addHeaders(headers, exchange.getRequest().getHeaders())) .exchange(); } } return result.flatMap(response -> response.toEntity(ParameterizedTypeReference.forType(type))); }
.accept(MediaType.APPLICATION_JSON) .headers(headers(clientRegistration)) .body(body) .exchange() .flatMap(response ->{
@Override public Mono<OAuth2AccessTokenResponse> getTokenResponse(OAuth2AuthorizationCodeGrantRequest authorizationGrantRequest) { return Mono.defer(() -> { ClientRegistration clientRegistration = authorizationGrantRequest.getClientRegistration(); OAuth2AuthorizationExchange authorizationExchange = authorizationGrantRequest.getAuthorizationExchange(); String tokenUri = clientRegistration.getProviderDetails().getTokenUri(); BodyInserters.FormInserter<String> body = body(authorizationExchange); return this.webClient.post() .uri(tokenUri) .accept(MediaType.APPLICATION_JSON) .headers(headers -> headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret())) .body(body) .exchange() .flatMap(response -> response.body(oauth2AccessTokenResponse())) .map(response -> { if (response.getAccessToken().getScopes().isEmpty()) { response = OAuth2AccessTokenResponse.withResponse(response) .scopes(authorizationExchange.getAuthorizationRequest().getScopes()) .build(); } return response; }); }); }
if (requiresBody(method)) { try { headersSpec = bodySpec.body(bodyInserter.get()); } catch (Exception ex) { return Mono.error(ex);
@Test public void postPerson() { final Mono<Person> body = webClient.post() .uri(uri("/birthday")) .contentType(MediaType.APPLICATION_JSON) .body(Mono.just(new Person("armeria", 4)), Person.class) .retrieve() .bodyToMono(Person.class); StepVerifier.create(body) .expectNext(new Person("armeria", 5)) .expectComplete() .verify(Duration.ofSeconds(10)); }