Java Code Examples for org.springframework.web.reactive.function.client.WebClient#RequestBodySpec

The following examples show how to use org.springframework.web.reactive.function.client.WebClient#RequestBodySpec . 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: WebClientPlugin.java    From soul with Apache License 2.0 6 votes vote down vote up
private Mono<Void> handleRequestBody(final WebClient.RequestBodySpec requestBodySpec,
                                     final ServerWebExchange exchange,
                                     final long timeout,
                                     final SoulPluginChain chain) {
    return requestBodySpec.headers(httpHeaders -> {
        httpHeaders.addAll(exchange.getRequest().getHeaders());
        httpHeaders.remove(HttpHeaders.HOST);
    })
            .contentType(buildMediaType(exchange))
            .body(BodyInserters.fromDataBuffers(exchange.getRequest().getBody()))
            .exchange()
            .doOnError(e -> log.error(e.getMessage()))
            .timeout(Duration.ofMillis(timeout))
            .flatMap(e -> doNext(e, exchange, chain));

}
 
Example 2
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private WebClient.RequestBodySpec prepareRequest(String path, HttpMethod method, Map<String, Object> pathParams, MultiValueMap<String, String> queryParams, Object body, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams, MultiValueMap<String, Object> formParams, List<MediaType> accept, MediaType contentType, String[] authNames) {
    updateParamsForAuth(authNames, queryParams, headerParams, cookieParams);

    final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path);
    if (queryParams != null) {
        builder.queryParams(queryParams);
    }

    final WebClient.RequestBodySpec requestBuilder = webClient.method(method).uri(builder.build(false).toUriString(), pathParams);
    if(accept != null) {
        requestBuilder.accept(accept.toArray(new MediaType[accept.size()]));
    }
    if(contentType != null) {
        requestBuilder.contentType(contentType);
    }

    addHeadersToRequest(headerParams, requestBuilder);
    addHeadersToRequest(defaultHeaders, requestBuilder);
    addCookiesToRequest(cookieParams, requestBuilder);
    addCookiesToRequest(defaultCookies, requestBuilder);

    requestBuilder.body(selectBody(body, formParams, contentType));
    return requestBuilder;
}
 
Example 3
Source File: InstanceWebProxy.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
public Mono<ClientResponse> forward(Instance instance, URI uri, HttpMethod method, HttpHeaders headers,
		BodyInserter<?, ? super ClientHttpRequest> bodyInserter) {
	log.trace("Proxy-Request for instance {} with URL '{}'", instance.getId(), uri);
	WebClient.RequestBodySpec bodySpec = this.instanceWebClient.instance(instance).method(method).uri(uri)
			.headers((h) -> h.addAll(headers));

	WebClient.RequestHeadersSpec<?> headersSpec = bodySpec;
	if (requiresBody(method)) {
		headersSpec = bodySpec.body(bodyInserter);
	}

	return headersSpec.exchange()
			.onErrorResume((ex) -> ex instanceof ReadTimeoutException || ex instanceof TimeoutException,
					(ex) -> Mono.fromSupplier(() -> {
						log.trace("Timeout for Proxy-Request for instance {} with URL '{}'", instance.getId(), uri);
						return ClientResponse.create(HttpStatus.GATEWAY_TIMEOUT, this.strategies).build();
					}))
			.onErrorResume(ResolveEndpointException.class, (ex) -> Mono.fromSupplier(() -> {
				log.trace("No Endpoint found for Proxy-Request for instance {} with URL '{}'", instance.getId(),
						uri);
				return ClientResponse.create(HttpStatus.NOT_FOUND, this.strategies).build();
			})).onErrorResume(IOException.class, (ex) -> Mono.fromSupplier(() -> {
				log.trace("Proxy-Request for instance {} with URL '{}' errored", instance.getId(), uri, ex);
				return ClientResponse.create(HttpStatus.BAD_GATEWAY, this.strategies).build();
			}));
}
 
Example 4
Source File: AbstractInstancesProxyController.java    From Moss with Apache License 2.0 5 votes vote down vote up
private Mono<ClientResponse> forward(Instance instance,
                                     URI uri,
                                     HttpMethod method,
                                     HttpHeaders headers,
                                     Supplier<BodyInserter<?, ? super ClientHttpRequest>> bodyInserter) {
    WebClient.RequestBodySpec bodySpec = instanceWebClient.instance(instance)
                                                          .method(method)
                                                          .uri(uri)
                                                          .headers(h -> h.addAll(filterHeaders(headers)));

    WebClient.RequestHeadersSpec<?> headersSpec = bodySpec;
    if (requiresBody(method)) {
        try {
            headersSpec = bodySpec.body(bodyInserter.get());
        } catch (Exception ex) {
            return Mono.error(ex);
        }
    }

    return headersSpec.exchange().onErrorResume(ReadTimeoutException.class, ex -> Mono.fromSupplier(() -> {
        log.trace("Timeout for Proxy-Request for instance {} with URL '{}'", instance.getId(), uri);
        return ClientResponse.create(HttpStatus.GATEWAY_TIMEOUT, strategies).build();
    })).onErrorResume(ResolveEndpointException.class, ex -> Mono.fromSupplier(() -> {
        log.trace("No Endpoint found for Proxy-Request for instance {} with URL '{}'", instance.getId(), uri);
        return ClientResponse.create(HttpStatus.NOT_FOUND, strategies).build();
    })).onErrorResume(IOException.class, ex -> Mono.fromSupplier(() -> {
        log.trace("Proxy-Request for instance {} with URL '{}' errored", instance.getId(), uri, ex);
        return ClientResponse.create(HttpStatus.BAD_GATEWAY, strategies).build();
    })).onErrorResume(ConnectException.class, ex -> Mono.fromSupplier(() -> {
        log.trace("Connect for Proxy-Request for instance {} with URL '{}' failed", instance.getId(), uri, ex);
        return ClientResponse.create(HttpStatus.BAD_GATEWAY, strategies).build();
    }));
}
 
Example 5
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Add headers to the request that is being built
 * @param headers The headers to add
 * @param requestBuilder The current request
 */
protected void addHeadersToRequest(HttpHeaders headers, WebClient.RequestBodySpec requestBuilder) {
    for (Entry<String, List<String>> entry : headers.entrySet()) {
        List<String> values = entry.getValue();
        for(String value : values) {
            if (value != null) {
                requestBuilder.header(entry.getKey(), value);
            }
        }
    }
}
 
Example 6
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Add cookies to the request that is being built
 * @param cookies The cookies to add
 * @param requestBuilder The current request
 */
protected void addCookiesToRequest(MultiValueMap<String, String> cookies, WebClient.RequestBodySpec requestBuilder) {
    for (Entry<String, List<String>> entry : cookies.entrySet()) {
        List<String> values = entry.getValue();
        for(String value : values) {
            if (value != null) {
                requestBuilder.cookie(entry.getKey(), value);
            }
        }
    }
}
 
Example 7
Source File: WebClientCallAdapterFactory.java    From spring-cloud-square with Apache License 2.0 5 votes vote down vote up
WebClient.RequestBodySpec requestBuilder(WebClient webClient, Request request) {
    WebClient.RequestBodySpec spec = webClient.mutate().build()
            .method(HttpMethod.resolve(request.method()))
            .uri(request.url().uri())
            .headers(httpHeaders -> {
                for (Map.Entry<String, List<String>> entry : request.headers().toMultimap().entrySet()) {
                    httpHeaders.put(entry.getKey(), entry.getValue());
                }
            });
    if (request.body() != null) {
        // spec.body()
        // FIXME: body
    }
    return spec;
}
 
Example 8
Source File: WebClientController.java    From tutorials with MIT License 5 votes vote down vote up
public void demonstrateWebClient() {
    // request
    WebClient.UriSpec<WebClient.RequestBodySpec> request1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST);
    WebClient.UriSpec<WebClient.RequestBodySpec> request2 = createWebClientWithServerURLAndDefaultValues().post();

    // request body specifications
    WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST)
        .uri("/resource");
    WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post()
        .uri(URI.create("/resource"));

    // request header specification
    WebClient.RequestHeadersSpec<?> requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class));
    WebClient.RequestHeadersSpec<?> requestSpec2 = uri2.body(BodyInserters.fromObject("data"));

    // inserters
    BodyInserter<Publisher<String>, ReactiveHttpOutputMessage> inserter1 = BodyInserters
            .fromPublisher(Subscriber::onComplete, String.class);

    LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("key1", "value1");
    map.add("key2", "value2");

    // BodyInserter<MultiValueMap<String, ?>, ClientHttpRequest> inserter2 = BodyInserters.fromMultipartData(map);
    BodyInserter<String, ReactiveHttpOutputMessage> inserter3 = BodyInserters.fromObject("body");

    // responses
    WebClient.ResponseSpec response1 = uri1.body(inserter3)
        .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
        .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
        .acceptCharset(Charset.forName("UTF-8"))
        .ifNoneMatch("*")
        .ifModifiedSince(ZonedDateTime.now())
        .retrieve();
    WebClient.ResponseSpec response2 = requestSpec2.retrieve();

}
 
Example 9
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 2 votes vote down vote up
/**
 * Invoke API by sending HTTP request with the given options.
 *
 * @param <T> the return type to use
 * @param path The sub-path of the HTTP URL
 * @param method The request method
 * @param pathParams The path parameters
 * @param queryParams The query parameters
 * @param body The request body object
 * @param headerParams The header parameters
 * @param formParams The form parameters
 * @param accept The request's Accept header
 * @param contentType The request's Content-Type header
 * @param authNames The authentications to apply
 * @param returnType The return type into which to deserialize the response
 * @return The response body in chosen type
 */
public <T> Mono<T> invokeAPI(String path, HttpMethod method, Map<String, Object> pathParams, MultiValueMap<String, String> queryParams, Object body, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams, MultiValueMap<String, Object> formParams, List<MediaType> accept, MediaType contentType, String[] authNames, ParameterizedTypeReference<T> returnType) throws RestClientException {
    final WebClient.RequestBodySpec requestBuilder = prepareRequest(path, method, pathParams, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames);
    return requestBuilder.retrieve().bodyToMono(returnType);
}
 
Example 10
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 2 votes vote down vote up
/**
 * Invoke API by sending HTTP request with the given options.
 *
 * @param <T> the return type to use
 * @param path The sub-path of the HTTP URL
 * @param method The request method
 * @param pathParams The path parameters
 * @param queryParams The query parameters
 * @param body The request body object
 * @param headerParams The header parameters
 * @param formParams The form parameters
 * @param accept The request's Accept header
 * @param contentType The request's Content-Type header
 * @param authNames The authentications to apply
 * @param returnType The return type into which to deserialize the response
 * @return The response body in chosen type
 */
public <T> Flux<T> invokeFluxAPI(String path, HttpMethod method, Map<String, Object> pathParams, MultiValueMap<String, String> queryParams, Object body, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams, MultiValueMap<String, Object> formParams, List<MediaType> accept, MediaType contentType, String[] authNames, ParameterizedTypeReference<T> returnType) throws RestClientException {
    final WebClient.RequestBodySpec requestBuilder = prepareRequest(path, method, pathParams, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames);
    return requestBuilder.retrieve().bodyToFlux(returnType);
}