body::get); requestBodySpec.contentType(MediaType.valueOf(request.getEntity().getContentType().getValue())); requestBodySpec.body(Mono.fromSupplier(body::get), String.class); } else {
@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); }
@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)); }
BTC_IN_SATOSHI.multiply(BigDecimal.ONE) .contentType(MediaType.APPLICATION_JSON_UTF8) .retrieve() .onStatus(HttpStatus::is4xxClientError, clientResponse -> clientResponse
@Bean public CommandLineRunner tweetBot(TwitterOAuth twitterOAuth, ReactiveTweetRepository tweetRepo) { return args -> { MultiValueMap<String, String> body = new LinkedMultiValueMap<>(); String tracks = "#cltjug,#FathersDay"; if (args.length > 0) { log.info("Using arguments as tracks"); tracks = String.join(",", args); } log.info("Filtering tracks [{}]", tracks); body.add("track", tracks); WebClient webClient = WebClient.create() .filter((currentRequest, next) -> next.exchange(ClientRequest.from(currentRequest) .header(HttpHeaders.AUTHORIZATION, twitterOAuth.oAuth1Header( currentRequest.url(), currentRequest.method(), body.toSingleValueMap())) .build())); Flux<Tweet> tweets = webClient .post() .uri(TwitterApiEndpoint.TWITTER_STREAM_API_STATUS_FILTER_URL) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .body(BodyInserters.fromFormData(body)) .exchange() .flatMapMany(clientResponse -> clientResponse.bodyToFlux(Tweet.class)); tweetRepo.saveAll(tweets).subscribe(System.out::println); }; }
private void redirectPost(EthereumAccount ethereumAccount, String uri, BigInteger nonce) { this.webClient .post() .uri(uri) .contentType(MediaType.APPLICATION_JSON_UTF8) .retrieve() .onStatus(HttpStatus::is4xxClientError, clientResponse -> clientResponse .bodyToMono(ByteArrayResource.class) .map(ByteArrayResource::getByteArray) .map(String::new) .map(ClientResponseException::new) ) .onStatus(HttpStatus::is5xxServerError, clientResponse -> clientResponse .bodyToMono(ByteArrayResource.class) .map(ByteArrayResource::getByteArray) .map(String::new) .map(ClientResponseException::new) ) .bodyToMono(String.class) .doOnSuccess(faucetResponseDto -> ethereumAccount.setNonce(null != nonce?nonce:BigInteger.ZERO)) .doOnError(RuntimeException::new) .block(); }
private void redirectPost(BitcoinAccount bitcoinAccount, String uri) { this.webClient .post() .uri(uri) .contentType(MediaType.APPLICATION_JSON_UTF8) .retrieve() .onStatus(HttpStatus::is4xxClientError, clientResponse -> clientResponse .bodyToMono(ByteArrayResource.class) .map(ByteArrayResource::getByteArray) .map(String::new) .map(ClientResponseException::new) ) .onStatus(HttpStatus::is5xxServerError, clientResponse -> clientResponse .bodyToMono(ByteArrayResource.class) .map(ByteArrayResource::getByteArray) .map(String::new) .map(ClientResponseException::new) ) .bodyToMono(String.class) .doOnSuccess(result -> this.addUtxo(bitcoinAccount, result)) .doOnError(RuntimeException::new) .block(); }
public static void main(String[] args) { int toBeSent = 257; Flux<String> flux = Flux.range(1, toBeSent).map(count -> { String result = "{\"content\":" + "\"" + count + "\"}"; if (count == 1) { return "[" + result; } else if (count == toBeSent) { return "," + result + "]"; } else { return "," + result; } }); WebClient client = WebClient.create(); ClientResponse result = client.post().uri(URI.create("http://localhost:8080/eventSink")) .contentType(MediaType.APPLICATION_JSON) .body(flux, String.class) .exchange() .block(); System.err.println(result.statusCode()); }
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(); }
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(); }
@Test public void shouldSendPojoAsJson() { prepareResponse(response -> response.setHeader("Content-Type", "application/json") .setBody("{\"bar\":\"BARBAR\",\"foo\":\"FOOFOO\"}")); Mono<Pojo> result = this.webClient.post() .uri("/pojo/capitalize") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .syncBody(new Pojo("foofoo", "barbar")) .retrieve() .bodyToMono(Pojo.class); StepVerifier.create(result) .consumeNextWith(p -> assertEquals("BARBAR", p.getBar())) .expectComplete() .verify(Duration.ofSeconds(3)); expectRequestCount(1); expectRequest(request -> { assertEquals("/pojo/capitalize", request.getPath()); assertEquals("{\"foo\":\"foofoo\",\"bar\":\"barbar\"}", request.getBody().readUtf8()); assertEquals("31", request.getHeader(HttpHeaders.CONTENT_LENGTH)); assertEquals("application/json", request.getHeader(HttpHeaders.ACCEPT)); assertEquals("application/json", request.getHeader(HttpHeaders.CONTENT_TYPE)); }); }