org.springframework.web.reactive.function.client.WebClient.RequestBodySpec Java Examples

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: AuthenticationStepsOperator.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
private Mono<Object> doHttpRequest(HttpRequestNode<Object> step, Object state) {

		HttpRequest<Object> definition = step.getDefinition();
		HttpEntity<?> entity = getEntity(definition.getEntity(), state);

		RequestBodySpec spec;
		if (definition.getUri() == null) {

			spec = this.webClient.method(definition.getMethod()).uri(definition.getUriTemplate(),
					definition.getUrlVariables());
		}
		else {
			spec = this.webClient.method(definition.getMethod()).uri(definition.getUri());
		}

		for (Entry<String, List<String>> header : entity.getHeaders().entrySet()) {
			spec = spec.header(header.getKey(), header.getValue().get(0));
		}

		if (entity.getBody() != null && !entity.getBody().equals(Undefinded.INSTANCE)) {
			return spec.bodyValue(entity.getBody()).retrieve().bodyToMono(definition.getResponseType());
		}

		return spec.retrieve().bodyToMono(definition.getResponseType());
	}
 
Example #2
Source File: ReactiveVaultTemplate.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<VaultResponse> write(String path, @Nullable Object body) {

	Assert.hasText(path, "Path must not be empty");

	return doWithSession(webClient -> {

		RequestBodySpec uri = webClient.post().uri(path);
		Mono<ClientResponse> exchange;
		if (body != null) {
			exchange = uri.bodyValue(body).exchange();
		}
		else {
			exchange = uri.exchange();
		}
		return exchange.flatMap(mapResponse(VaultResponse.class, path, HttpMethod.POST));
	});
}
 
Example #3
Source File: ProxyExchange.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
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.fromValue(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)));
}
 
Example #4
Source File: ApiProxyController.java    From demo-spring-webflux-api-gateway with Apache License 2.0 4 votes vote down vote up
/**
    * 
    * @param exchange 
    * @return
    */
   @RequestMapping("/**")
   public Mono<Void>  proxyRequest(ServerWebExchange exchange)
{
	ServerHttpRequest frontEndReq = exchange.getRequest();
	ServerHttpResponse frontEndResp = exchange.getResponse();
	String path = frontEndReq.getPath().pathWithinApplication().value();
	HttpMethod httpMethod = frontEndReq.getMethod();
	RequestBodySpec reqBodySpec = webClient.method(httpMethod).
			uri(backendServiceUrlPrefix.concat(path)).
			headers(httpHeaders -> 
			        {
	                  httpHeaders.addAll(frontEndReq.getHeaders());
	                  httpHeaders.remove("HOST");
	                });
	
	RequestHeadersSpec<?> reqHeadersSpec;
    if (requireHttpBody(httpMethod)) {
    		  reqHeadersSpec = reqBodySpec.body(BodyInserters.fromDataBuffers(frontEndReq.getBody()));
    } else {
    	      reqHeadersSpec = reqBodySpec;
    	}
    
	//调用后端服务
	return reqHeadersSpec.exchange().timeout(Duration.ofMillis(backendServiceTimeoutInMillis)).
			onErrorResume(ex -> 
		    { 
			    //调用后端服务异常(超时、网络问题)时,转发到后端异常-后控制器
		    	    //此处也可不用转发,用frontEndResp.writeWith(...)直接将异常响应写回给调用方
		    	    Map<String,Object> forwardAttrs = new HashMap<>();
		    	    forwardAttrs.put(Constant.BACKEND_EXCEPTION_ATTR_NAME,ex);
                return WebfluxForwardingUtil.forward(Constant.BACKEND_EXCEPTION_PATH,exchange,forwardAttrs)
                		.then(Mono.empty());
			}).flatMap(backendResponse -> 
		    {
		    	    //将后端服务的响应回写到前端resp
		    	    frontEndResp.setStatusCode(backendResponse.statusCode());
		    	    frontEndResp.getHeaders().putAll(backendResponse.headers().asHttpHeaders());
		    	    return frontEndResp.writeWith(backendResponse.bodyToFlux(DataBuffer.class));
		    	}
		    	);
}
 
Example #5
Source File: WebClientHttpRoutingFilter.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);

	String scheme = requestUrl.getScheme();
	if (isAlreadyRouted(exchange)
			|| (!"http".equals(scheme) && !"https".equals(scheme))) {
		return chain.filter(exchange);
	}
	setAlreadyRouted(exchange);

	ServerHttpRequest request = exchange.getRequest();

	HttpMethod method = request.getMethod();

	HttpHeaders filteredHeaders = filterRequest(getHeadersFilters(), exchange);

	boolean preserveHost = exchange
			.getAttributeOrDefault(PRESERVE_HOST_HEADER_ATTRIBUTE, false);

	RequestBodySpec bodySpec = this.webClient.method(method).uri(requestUrl)
			.headers(httpHeaders -> {
				httpHeaders.addAll(filteredHeaders);
				// TODO: can this support preserviceHostHeader?
				if (!preserveHost) {
					httpHeaders.remove(HttpHeaders.HOST);
				}
			});

	RequestHeadersSpec<?> headersSpec;
	if (requiresBody(method)) {
		headersSpec = bodySpec.body(BodyInserters.fromDataBuffers(request.getBody()));
	}
	else {
		headersSpec = bodySpec;
	}

	return headersSpec.exchange()
			// .log("webClient route")
			.flatMap(res -> {
				ServerHttpResponse response = exchange.getResponse();
				response.getHeaders().putAll(res.headers().asHttpHeaders());
				response.setStatusCode(res.statusCode());
				// Defer committing the response until all route filters have run
				// Put client response as ServerWebExchange attribute and write
				// response later NettyWriteResponseFilter
				exchange.getAttributes().put(CLIENT_RESPONSE_ATTR, res);
				return chain.filter(exchange);
			});
}