org.springframework.web.reactive.function.client.ClientResponse Java Examples

The following examples show how to use org.springframework.web.reactive.function.client.ClientResponse. 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: CorsTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void testPreFlightCorsRequest() {
	ClientResponse clientResponse = webClient.options().uri("/abc/123/function")
			.header("Origin", "domain.com")
			.header("Access-Control-Request-Method", "GET").exchange().block();
	HttpHeaders asHttpHeaders = clientResponse.headers().asHttpHeaders();
	Mono<String> bodyToMono = clientResponse.bodyToMono(String.class);
	// pre-flight request shouldn't return the response body
	assertThat(bodyToMono.block()).isNull();
	assertThat(asHttpHeaders.getAccessControlAllowOrigin())
			.as("Missing header value in response: "
					+ HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)
			.isEqualTo("*");
	assertThat(asHttpHeaders.getAccessControlAllowMethods())
			.as("Missing header value in response: "
					+ HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)
			.isEqualTo(Arrays.asList(new HttpMethod[] { HttpMethod.GET }));
	assertThat(clientResponse.statusCode()).as("Pre Flight call failed.")
			.isEqualTo(HttpStatus.OK);
}
 
Example #2
Source File: TraceWebClientBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Override
public void onNext(ClientResponse response) {
	try (Scope scope = currentTraceContext.maybeScope(parent)) {
		// decorate response body
		this.actual
				.onNext(ClientResponse.from(response)
						.body(response.bodyToFlux(DataBuffer.class)
								.transform(this.scopePassingTransformer))
						.build());
	}
	finally {
		Span span = getAndSet(null);
		if (span != null) {
			// TODO: is there a way to read the request at response time?
			this.handler.handleReceive(new ClientResponseWrapper(response), null,
					span);
		}
	}
}
 
Example #3
Source File: ModifyResponseBodyGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
private <T> Mono<T> extractBody(ServerWebExchange exchange,
		ClientResponse clientResponse, Class<T> inClass) {
	// if inClass is byte[] then just return body, otherwise check if
	// decoding required
	if (byte[].class.isAssignableFrom(inClass)) {
		return clientResponse.bodyToMono(inClass);
	}

	List<String> encodingHeaders = exchange.getResponse().getHeaders()
			.getOrEmpty(HttpHeaders.CONTENT_ENCODING);
	for (String encoding : encodingHeaders) {
		MessageBodyDecoder decoder = messageBodyDecoders.get(encoding);
		if (decoder != null) {
			return clientResponse.bodyToMono(byte[].class)
					.publishOn(Schedulers.parallel()).map(decoder::decode)
					.map(bytes -> exchange.getResponse().bufferFactory()
							.wrap(bytes))
					.map(buffer -> prepareClientResponse(Mono.just(buffer),
							exchange.getResponse().getHeaders()))
					.flatMap(response -> response.bodyToMono(inClass));
		}
	}

	return clientResponse.bodyToMono(inClass);
}
 
Example #4
Source File: EurekaLoadBalancingExchangeFilterFunction.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private Mono<ClientResponse> doExecute(InstanceInfo instance, ClientRequest request, ExchangeFunction next) {
    URI eurekaUri = request.url();
    URI rewrittenURI = rewrite(eurekaUri, instance);

    ClientRequest newRequest = ClientRequest.create(request.method(), rewrittenURI)
            .headers(headers -> headers.addAll(request.headers()))
            .cookies(cookies -> cookies.addAll(request.cookies()))
            .attributes(attributes -> attributes.putAll(request.attributes()))
            .body(request.body()).build();
    return next.exchange(newRequest)
            .doOnNext(response -> {
                if (response.statusCode().is5xxServerError()) {
                    loadBalancer.recordFailure(eurekaUri, instance);
                } else {
                    loadBalancer.recordSuccess(eurekaUri, instance);
                }
            })
            .doOnError(error -> loadBalancer.recordFailure(eurekaUri, instance));
}
 
Example #5
Source File: SupplierExporter.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
private Mono<ClientResponse> post(URI uri, String destination, Object value) {
	Object body = value;
	if (value instanceof Message) {
		Message<?> message = (Message<?>) value;
		body = message.getPayload();
	}
	if (this.debug) {
		logger.debug("Sending BODY as type: " + body.getClass().getName());
	}
	Mono<ClientResponse> result = this.client.post().uri(uri)
			.headers(headers -> headers(headers, destination, value)).bodyValue(body)
			.exchange()
			.doOnNext(response -> {
				if (this.debug) {
					logger.debug("Response STATUS: " + response.statusCode());
				}
			});
	if (this.debug) {
		result = result.log();
	}
	return result;
}
 
Example #6
Source File: WingtipsSpringWebfluxExchangeFilterFunctionTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@Test
public void WingtipsExchangeFilterFunctionTracingCompletionMonoWrapper_constructor_sets_fields_as_expected() {
    // given
    @SuppressWarnings("unchecked")
    Mono<ClientResponse> sourceMock = mock(Mono.class);
    TracingState tracingStateMock = mock(TracingState.class);
    
    // when
    WingtipsExchangeFilterFunctionTracingCompletionMonoWrapper impl =
        new WingtipsExchangeFilterFunctionTracingCompletionMonoWrapper(
            sourceMock, request, tracingStateMock, tagAndNamingStrategy, tagAndNamingAdapterMock
        );

    // then
    assertThat(impl.request).isSameAs(request);
    assertThat(impl.spanAroundCallTracingState).isSameAs(tracingStateMock);
    assertThat(impl.tagAndNamingStrategy).isSameAs(tagAndNamingStrategy);
    assertThat(impl.tagAndNamingAdapter).isSameAs(tagAndNamingAdapterMock);
}
 
Example #7
Source File: InstanceExchangeFilterFunctionsTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_convert_v1_actuator() {
    ExchangeFilterFunction filter = InstanceExchangeFilterFunctions.convertLegacyEndpoint(new TestLegacyEndpointConverter());

    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test"))
                                         .attribute(ATTRIBUTE_ENDPOINT, "test")
                                         .build();
    ClientResponse response = ClientResponse.create(HttpStatus.OK)
                                            .header(CONTENT_TYPE, ActuatorMediaType.V1_JSON)
                                            .body(Flux.just(ORIGINAL))
                                            .build();

    Mono<ClientResponse> convertedResponse = filter.filter(request, r -> Mono.just(response));

    StepVerifier.create(convertedResponse)
                .assertNext(r -> StepVerifier.create(r.body(BodyExtractors.toDataBuffers()))
                                             .expectNext(CONVERTED)
                                             .verifyComplete())
                .verifyComplete();
}
 
Example #8
Source File: InstanceExchangeFilterFunctionsTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
void should_not_convert_unknown_endpoint() {
	InstanceExchangeFilterFunction filter = InstanceExchangeFilterFunctions.convertLegacyEndpoints(
			singletonList(new LegacyEndpointConverter("test", (from) -> Flux.just(this.converted)) {
			}));

	ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test")).build();
	ClientResponse response = ClientResponse.create(HttpStatus.OK).header(CONTENT_TYPE, APPLICATION_JSON_VALUE)
			.header(CONTENT_LENGTH, Integer.toString(this.original.readableByteCount()))
			.body(Flux.just(this.original)).build();

	Mono<ClientResponse> convertedResponse = filter.filter(INSTANCE, request, (r) -> Mono.just(response));

	StepVerifier.create(convertedResponse).assertNext((r) -> {
		assertThat(r.headers().contentType()).hasValue(MediaType.APPLICATION_JSON);
		assertThat(r.headers().contentLength()).hasValue(this.original.readableByteCount());
		StepVerifier.create(r.body(BodyExtractors.toDataBuffers())).expectNext(this.original).verifyComplete();
	}).verifyComplete();
}
 
Example #9
Source File: SimpleUrlHandlerCorsTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void testPreFlightCorsRequestNotHandledByGW() {
	ClientResponse clientResponse = webClient.options().uri("/abc/123/function")
			.header("Origin", "domain.com")
			.header("Access-Control-Request-Method", "GET").exchange().block();
	HttpHeaders asHttpHeaders = clientResponse.headers().asHttpHeaders();
	Mono<String> bodyToMono = clientResponse.bodyToMono(String.class);
	// pre-flight request shouldn't return the response body
	assertThat(bodyToMono.block()).isNull();
	assertThat(asHttpHeaders.getAccessControlAllowOrigin())
			.as("Missing header value in response: "
					+ HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)
			.isEqualTo("*");
	assertThat(asHttpHeaders.getAccessControlAllowMethods())
			.as("Missing header value in response: "
					+ HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS)
			.isEqualTo(Arrays.asList(new HttpMethod[] { HttpMethod.GET }));
	assertThat(clientResponse.statusCode()).as("Pre Flight call failed.")
			.isEqualTo(HttpStatus.OK);
}
 
Example #10
Source File: TraceWebClientBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Override
public void subscribe(CoreSubscriber<? super ClientResponse> subscriber) {

	Context context = subscriber.currentContext();

	ClientRequestWrapper wrapper = new ClientRequestWrapper(request);
	Span span = handler.handleSendWithParent(wrapper, parent);
	if (log.isDebugEnabled()) {
		log.debug("HttpClientHandler::handleSend: " + span);
	}

	// NOTE: We are starting the client span for the request here, but it could be
	// canceled prior to actually being invoked. TraceWebClientSubscription will
	// abandon this span, if cancel() happens before request().
	this.next.exchange(wrapper.buildRequest()).subscribe(
			new TraceWebClientSubscriber(subscriber, context, span, this));
}
 
Example #11
Source File: InstanceExchangeFilterFunctionsTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_convert_json() {
    ExchangeFilterFunction filter = InstanceExchangeFilterFunctions.convertLegacyEndpoint(new TestLegacyEndpointConverter());

    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test"))
                                         .attribute(ATTRIBUTE_ENDPOINT, "test")
                                         .build();
    ClientResponse response = ClientResponse.create(HttpStatus.OK)
                                            .header(CONTENT_TYPE, APPLICATION_JSON_VALUE)
                                            .body(Flux.just(ORIGINAL))
                                            .build();

    Mono<ClientResponse> convertedResponse = filter.filter(request, r -> Mono.just(response));

    StepVerifier.create(convertedResponse)
                .assertNext(r -> StepVerifier.create(r.body(BodyExtractors.toDataBuffers()))
                                             .expectNext(CONVERTED)
                                             .verifyComplete())
                .verifyComplete();
}
 
Example #12
Source File: InstanceExchangeFilterFunctionsTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_not_convert_v2_actuator() {
    ExchangeFilterFunction filter = InstanceExchangeFilterFunctions.convertLegacyEndpoint(new TestLegacyEndpointConverter());

    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test"))
                                         .attribute(ATTRIBUTE_ENDPOINT, "test")
                                         .build();
    ClientResponse response = ClientResponse.create(HttpStatus.OK)
                                            .header(CONTENT_TYPE, ActuatorMediaType.V2_JSON)
                                            .body(Flux.just(ORIGINAL))
                                            .build();

    Mono<ClientResponse> convertedResponse = filter.filter(request, r -> Mono.just(response));

    StepVerifier.create(convertedResponse)
                .assertNext(r -> StepVerifier.create(r.body(BodyExtractors.toDataBuffers()))
                                             .expectNext(ORIGINAL)
                                             .verifyComplete())
                .verifyComplete();
}
 
Example #13
Source File: InstanceExchangeFilterFunctionsTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_retry_using_default() {
    ExchangeFilterFunction filter = InstanceExchangeFilterFunctions.retry(1, emptyMap());

    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test")).build();
    ClientResponse response = mock(ClientResponse.class);

    AtomicLong invocationCount = new AtomicLong(0L);
    ExchangeFunction exchange = r -> Mono.fromSupplier(() -> {
        if (invocationCount.getAndIncrement() == 0) {
            throw new IllegalStateException("Test");
        }
        return response;
    });

    StepVerifier.create(filter.filter(request, exchange)).expectNext(response).verifyComplete();
    assertThat(invocationCount.get()).isEqualTo(2);
}
 
Example #14
Source File: ResultPipe.java    From bird-java with MIT License 6 votes vote down vote up
@Override
protected Mono<Void> doExecute(ServerWebExchange exchange, PipeChain chain, RouteDefinition routeDefinition) {
    return chain.execute(exchange).then(Mono.defer(() -> {
        ServerHttpResponse response = exchange.getResponse();
        final String resultType = exchange.getAttribute(GatewayConstant.RESPONSE_RESULT_TYPE);
        RpcTypeEnum rpcTypeEnum = RpcTypeEnum.acquireByName(routeDefinition.getRpcType());

        if(RpcTypeEnum.SPRING_CLOUD.getName().equals(rpcTypeEnum.getName())){
            ClientResponse clientResponse = exchange.getAttribute(GatewayConstant.HTTP_RPC_RESULT);
            if (Objects.isNull(clientResponse)) {
                return jsonResult(exchange,JsonResult.error("服务端无响应."));
            }
            return response.writeWith(clientResponse.body(BodyExtractors.toDataBuffers()));

        }else if(RpcTypeEnum.DUBBO.getName().equals(rpcTypeEnum.getName())){
            if(StringUtils.equalsIgnoreCase(resultType,ResultEnum.SUCCESS.getName())){
                final Object result = exchange.getAttribute(GatewayConstant.DUBBO_RPC_RESULT);
                return jsonResult(exchange,JsonResult.success(result));
            }else {
                final String message = exchange.getAttribute(GatewayConstant.DUBBO_ERROR_MESSAGE);
                return jsonResult(exchange,JsonResult.error(message));
            }
        }
        return Mono.empty();
    }));
}
 
Example #15
Source File: SubnetManagerServiceProxy.java    From alcor with Apache License 2.0 6 votes vote down vote up
public Mono<SubnetsWebJson> findSubnets(UUID projectId) {
    Mono<ClientResponse> response = webClient
            .get()
            .uri(webDestinations.getSubnetManagerServiceUrl() + "/project/{projectId}/subnets", projectId)
            .exchange();
    return response.flatMap(resp -> {
        switch (resp.statusCode()) {
            case OK:
                return resp.bodyToMono(SubnetsWebJson.class);
            case NOT_FOUND:
                return Mono.error(new SubnetNotFoundException());
            default:
                return Mono.error(new RuntimeException("Unknown" + resp.statusCode()));
        }
    });
}
 
Example #16
Source File: SubnetManagerServiceProxy.java    From alcor with Apache License 2.0 6 votes vote down vote up
public Mono<SubnetWebJson> createSubnet(UUID projectId, Mono<SubnetWebJson> newSubnetJson) {
    Mono<ClientResponse> response = webClient
            .post()
            .uri(webDestinations.getSubnetManagerServiceUrl() + "/project/{projectId}/subnets", projectId)
            .body(newSubnetJson, SubnetWebJson.class)
            .exchange();
    return response.flatMap(resp -> {
        switch (resp.statusCode()) {
            case CREATED:
                return resp.bodyToMono(SubnetWebJson.class);
            case NOT_FOUND:
                return Mono.error(new SubnetNotFoundException());
            default:
                return Mono.error(new RuntimeException("Unknown" + resp.statusCode()));
        }
    });
}
 
Example #17
Source File: InstanceExchangeFilterFunctionsTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
void should_convert_v1_actuator() {
	ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test"))
			.attribute(ATTRIBUTE_ENDPOINT, "test").build();
	@SuppressWarnings("deprecation")
	ClientResponse legacyResponse = ClientResponse.create(HttpStatus.OK)
			.header(CONTENT_TYPE, ACTUATOR_V1_MEDIATYPE.toString())
			.header(CONTENT_LENGTH, Integer.toString(this.original.readableByteCount()))
			.body(Flux.just(this.original)).build();

	Mono<ClientResponse> response = this.filter.filter(INSTANCE, request, (r) -> Mono.just(legacyResponse));

	StepVerifier.create(response).assertNext((r) -> {
		assertThat(r.headers().contentType()).hasValue(MediaType.valueOf(ActuatorMediaType.V2_JSON));
		assertThat(r.headers().contentLength()).isEmpty();
		StepVerifier.create(r.body(BodyExtractors.toDataBuffers())).expectNext(this.converted).verifyComplete();
	}).verifyComplete();
}
 
Example #18
Source File: InstanceExchangeFilterFunctionsTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
void should_not_convert_without_converter() {
	InstanceExchangeFilterFunction filter = InstanceExchangeFilterFunctions.convertLegacyEndpoints(
			singletonList(new LegacyEndpointConverter("test", (from) -> Flux.just(this.converted)) {
			}));

	ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/unknown"))
			.attribute(ATTRIBUTE_ENDPOINT, "unknown").build();
	ClientResponse response = ClientResponse.create(HttpStatus.OK).header(CONTENT_TYPE, APPLICATION_JSON_VALUE)
			.header(CONTENT_LENGTH, Integer.toString(this.original.readableByteCount()))
			.body(Flux.just(this.original)).build();

	Mono<ClientResponse> convertedResponse = filter.filter(INSTANCE, request, (r) -> Mono.just(response));

	StepVerifier.create(convertedResponse).assertNext((r) -> {
		assertThat(r.headers().contentType()).hasValue(MediaType.APPLICATION_JSON);
		assertThat(r.headers().contentLength()).hasValue(this.original.readableByteCount());
		StepVerifier.create(r.body(BodyExtractors.toDataBuffers())).expectNext(this.original).verifyComplete();
	}).verifyComplete();
}
 
Example #19
Source File: WingtipsSpringWebfluxExchangeFilterFunction.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@Override
public void subscribe(
    @NotNull CoreSubscriber<? super ClientResponse> actual
) {
    // The request will be kicked off as part of the source.subscribe(...) call, so wrap it in
    //      a runnableWithTracing(...) so it has the correct tracing state.
    runnableWithTracing(
        () -> {
            // Wrap the actual subscriber with a WingtipsExchangeFilterFunctionTracingCompletionSubscriber
            //      in order to complete the subspan when the source Mono finishes.
            source.subscribe(
                new WingtipsExchangeFilterFunctionTracingCompletionSubscriber(
                    actual,
                    request,
                    actual.currentContext(),
                    spanAroundCallTracingState,
                    tagAndNamingStrategy,
                    tagAndNamingAdapter
                )
            );
        },
        spanAroundCallTracingState
    ).run();
}
 
Example #20
Source File: InstanceExchangeFilterFunctionsTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
void should_retry_using_endpoint_value_default() {
	InstanceExchangeFilterFunction filter = InstanceExchangeFilterFunctions.retry(0, singletonMap("test", 1));

	ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test"))
			.attribute(ATTRIBUTE_ENDPOINT, "test").build();
	ClientResponse response = ClientResponse.create(HttpStatus.OK).build();

	AtomicLong invocationCount = new AtomicLong(0L);
	ExchangeFunction exchange = (r) -> Mono.fromSupplier(() -> {
		if (invocationCount.getAndIncrement() == 0) {
			throw new IllegalStateException("Test");
		}
		return response;
	});

	StepVerifier.create(filter.filter(INSTANCE, request, exchange)).expectNext(response).verifyComplete();
	assertThat(invocationCount.get()).isEqualTo(2);
}
 
Example #21
Source File: TraceWebFluxTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
private void thenNoSpanWasReported(TestSpanHandler spans, ClientResponse response,
		Controller2 controller2) {
	Awaitility.await().untilAsserted(() -> {
		then(response.statusCode().value()).isEqualTo(200);
		then(spans).isEmpty();
	});
	then(controller2.span).isNotNull();
	then(controller2.span.context().traceIdString()).isEqualTo(EXPECTED_TRACE_ID);
}
 
Example #22
Source File: WebClientBraveTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Override
Mono<Integer> postMono(AnnotationConfigApplicationContext context,
		String pathIncludingQuery, String body) {
	return context.getBean(WebClient.Builder.class).build().post()
			.uri(pathIncludingQuery).body(BodyInserters.fromValue(body)).exchange()
			.map(ClientResponse::rawStatusCode);
}
 
Example #23
Source File: ModifyResponseBodyGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
private ClientResponse prepareClientResponse(Publisher<? extends DataBuffer> body,
		HttpHeaders httpHeaders) {
	ClientResponse.Builder builder;
	builder = ClientResponse.create(exchange.getResponse().getStatusCode(),
			messageReaders);
	return builder.headers(headers -> headers.putAll(httpHeaders))
			.body(Flux.from(body)).build();
}
 
Example #24
Source File: UsersClient.java    From blog-tutorials with MIT License 5 votes vote down vote up
public JsonNode createNewUser(JsonNode payload) {
  ClientResponse clientResponse = this.webClient
    .post()
    .uri("/users")
    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
    .bodyValue(payload)
    .exchange()
    .block();

  if (clientResponse.statusCode().equals(HttpStatus.CREATED)) {
    return clientResponse.bodyToMono(JsonNode.class).block();
  } else {
    throw new RuntimeException("Unable to create new user!");
  }
}
 
Example #25
Source File: InstanceExchangeFilterFunctionsTest.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Test
void should_rewirte_url_and_add_endpoint_attribute() {
	ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("health/database"))
			.attribute(ATTRIBUTE_INSTANCE, this.instance).build();

	Mono<ClientResponse> response = this.filter.filter(this.instance, request, (req) -> {
		assertThat(req.url()).isEqualTo(URI.create(this.registration.getHealthUrl() + "/database"));
		assertThat(req.attribute(ATTRIBUTE_ENDPOINT)).hasValue(Endpoint.HEALTH);
		return Mono.just(ClientResponse.create(HttpStatus.OK).build());
	});

	StepVerifier.create(response).expectNextCount(1).verifyComplete();
}
 
Example #26
Source File: ClientReactiveController.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@RequestMapping(value="/reactSaveEmp", consumes= MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String hello(@RequestBody Employee employee){
	 Mono<ClientResponse> resp = WebClient.create().post().uri("http://localhost:8908/saveEmp").accept(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromObject(employee)).exchange();
	 return resp.block().statusCode().name();
 }
 
Example #27
Source File: RemoteAddrRoutePredicateFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void remoteAddrRejects() {
	Mono<ClientResponse> result = webClient.get().uri("/nok/httpbin/").exchange();

	StepVerifier.create(result)
			.consumeNextWith(response -> assertStatus(response, HttpStatus.NOT_FOUND))
			.expectComplete().verify(DURATION);
}
 
Example #28
Source File: HttpSupplier.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
private Object message(ClientResponse response, Object payload) {
	if (!this.props.getSource().isIncludeHeaders()) {
		return payload;
	}
	return MessageBuilder.withPayload(payload)
			.copyHeaders(HeaderUtils.fromHttp(
					HeaderUtils.sanitize(response.headers().asHttpHeaders())))
			.setHeader("scf-sink-url", this.props.getSink().getUrl())
			.setHeader("scf-func-name", this.props.getSink().getName())
			.build();
}
 
Example #29
Source File: InfoUpdater.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
protected Mono<Info> convertInfo(Instance instance, ClientResponse response) {
	if (response.statusCode().is2xxSuccessful() && response.headers().contentType().map(
			(mt) -> mt.isCompatibleWith(MediaType.APPLICATION_JSON) || mt.isCompatibleWith(ACTUATOR_V2_MEDIATYPE))
			.orElse(false)) {
		return response.bodyToMono(RESPONSE_TYPE).map(Info::from).defaultIfEmpty(Info.empty());
	}
	log.info("Couldn't retrieve info for {}: {}", instance, response.statusCode());
	return response.releaseBody().then(Mono.just(Info.empty()));
}
 
Example #30
Source File: WebClientRequestsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Before
public void init() {
    MockitoAnnotations.initMocks(this);
    this.exchangeFunction = mock(ExchangeFunction.class);
    ClientResponse mockResponse = mock(ClientResponse.class);
    when(this.exchangeFunction.exchange(this.argumentCaptor.capture())).thenReturn(Mono.just(mockResponse));
    this.webClient = WebClient
            .builder()
            .baseUrl(BASE_URL)
            .exchangeFunction(exchangeFunction)
            .build();
}