当前位置: 首页>>代码示例>>Java>>正文


Java WebClient类代码示例

本文整理汇总了Java中org.springframework.web.reactive.function.client.WebClient的典型用法代码示例。如果您正苦于以下问题:Java WebClient类的具体用法?Java WebClient怎么用?Java WebClient使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


WebClient类属于org.springframework.web.reactive.function.client包,在下文中一共展示了WebClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: mockWebClient

import org.springframework.web.reactive.function.client.WebClient; //导入依赖的package包/类
public static WebClient mockWebClient(final WebClient originalClient, final Mono<?> mono){
    WebClient client = spy(originalClient);

    WebClient.UriSpec uriSpec = mock(WebClient.UriSpec.class);
    doReturn(uriSpec).when(client).get();

    WebClient.RequestHeadersSpec<?> headerSpec = mock(WebClient.RequestHeadersSpec.class);
    doReturn(headerSpec).when(uriSpec).uri(anyString());
    doReturn(headerSpec).when(headerSpec).accept(any());

    ClientResponse clientResponse = mock(ClientResponse.class);
    doReturn(mono).when(clientResponse).bodyToMono(Mockito.any());
    doReturn(Mono.just(clientResponse)).when(headerSpec).exchange();

    return client;
}
 
开发者ID:LearningByExample,项目名称:reactive-ms-example,代码行数:17,代码来源:RestServiceHelper.java

示例2: configure

import org.springframework.web.reactive.function.client.WebClient; //导入依赖的package包/类
<S extends WebClient.RequestHeadersSpec<S>> Mono<S> configure(
		WebClient.RequestHeadersUriSpec<S> spec, String applicationId,
		ServerHttpRequest request) {
	Mono<Application> applicationMono = this.applicationRepository
			.findById(applicationId);
	Mono<AccessToken> accessTokenMono = this.accessTokenService
			.issueToken(applicationId);

	// / proxy / {applicationId} / **
	// ^___^___^________^________^__^
	// 0___1___2________3________4__5
	PathContainer wildcard = request.getPath().subPath(5);

	return Mono.when(applicationMono, accessTokenMono) //
			.map(tpl -> spec
					.uri(tpl.getT1().getUrl() + "/cloudfoundryapplication/"
							+ wildcard.value())
					.header(AUTHORIZATION, "bearer " + tpl.getT2().getToken()) //
					.header(REFERER, request.getHeaders().getFirst(REFERER)));
}
 
开发者ID:making,项目名称:spring-boot-actuator-dashboard,代码行数:21,代码来源:ProxyController.java

示例3: callSSOProvider

import org.springframework.web.reactive.function.client.WebClient; //导入依赖的package包/类
public Mono<User> callSSOProvider(String accessToken, SSOProvider ssoProvider) {
    SSOProperties.SSOValues keys = ssoProperties.getProviders().get(ssoProvider);
    return WebClient.builder()
            .build()
            .get()
            .uri(keys.getProfileUrl())
            .header(HttpHeaders.AUTHORIZATION, OAuth2AccessToken.BEARER_TYPE + " " + accessToken)
            .exchange()
            .flatMap(resp -> resp.bodyToMono(Map.class))
            .flatMap(body -> {
                if(Integer.valueOf(401).equals(body.get("status"))){
                    return Mono.error(new ResponseStatusException(HttpStatus.UNAUTHORIZED, body.get("message").toString()));
                } else {
                    return Mono.just(body);
                }
            })
            .map(values -> new TokenService.UserSSO(values, keys))
            .map(userSSO -> {
                User user = new User();
                user.setIdSSO(ssoProvider.toString() + "#" + userSSO.id);
                user.setFirstName(userSSO.firstName);
                user.setLastName(userSSO.lastName);
                return user;
            });
}
 
开发者ID:SopraSteriaGroup,项目名称:initiatives_backend_auth,代码行数:26,代码来源:TokenService.java

示例4: requestToken

import org.springframework.web.reactive.function.client.WebClient; //导入依赖的package包/类
/**
 * Request an OAuth2 token from the Authentication Server
 * 
 * @param webClient The webClient to connect with
 * 
 * @return The token
 */
private String requestToken(WebClient webClient) {

	/* Add Basic Authentication to the WebClient */
	final WebClient webClientAuth = webClient.mutate().filter(basicAuthentication("clientId", "clientSecret")).build();
	
	return webClientAuth.post().uri("/oauth/token")
		.contentType(APPLICATION_FORM_URLENCODED)
		.accept(APPLICATION_JSON_UTF8)
		.body(fromObject("grant_type=client_credentials"))
		.retrieve()
		.bodyToMono(JsonNode.class)
		.map(node -> node.get("access_token"))
		.map(token -> token.asText())
		.block();
		
}
 
开发者ID:dserradji,项目名称:reactive-customer-service,代码行数:24,代码来源:CustomerServiceTest.java

示例5: insertCoinbaseQuote

import org.springframework.web.reactive.function.client.WebClient; //导入依赖的package包/类
@Scheduled(fixedRate = 60000, initialDelay=15000)
	public void insertCoinbaseQuote() {
		Date start = new Date();
		WebClient wc = buildWebClient(URLCB);
		try {
			operations.insert(
					wc.get().uri("/exchange-rates?currency=BTC")
	                .accept(MediaType.APPLICATION_JSON).exchange()
	                .flatMap(response ->	response.bodyToMono(WrapperCb.class))
	                .flatMap(resp -> Mono.just(resp.getData()))
	                .flatMap(resp2 -> {log.info(resp2.getRates().toString()); return Mono.just(resp2.getRates());})
					).then().block(Duration.ofSeconds(3));
			log.info("CoinbaseQuote " + dateFormat.format(new Date()) + " " + (new Date().getTime()-start.getTime()) + "ms");
		} catch (Exception e) {
//			log.error("Coinbase insert error", e);
			log.error("Coinbase insert error "+ dateFormat.format(new Date()));
		}
	}
 
开发者ID:Angular2Guy,项目名称:AngularAndSpring,代码行数:19,代码来源:ScheduledTask.java

示例6: performRequest

import org.springframework.web.reactive.function.client.WebClient; //导入依赖的package包/类
private <T extends WebClient.RequestHeadersSpec<T>> Mono<IpfsResult> performRequest(WebClient.RequestHeadersSpec<T> request) {
    return request
        .header(CONTENT_TRANSFER_ENCODING,"chunked")
        .accept(APPLICATION_JSON)
        .exchange()
        .flatMap(response -> {
            if (response.statusCode().is2xxSuccessful()) {
                return response.bodyToMono(BlockPersistenceResponse.class)
                        .map(blockResponse -> new IpfsResult(response.statusCode().value(), blockResponse));
            } else {
                return Mono.fromSupplier(() -> new IpfsResult(response.statusCode().value(), null));
            }
        })
        .doOnSuccess(response -> log.info("Block persistence result: {}", response))
        .doOnError(error -> log.error("Block persistence failed", error));
}
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:17,代码来源:IpfsLogsStorage.java

示例7: augmentWithSelfLookup

import org.springframework.web.reactive.function.client.WebClient; //导入依赖的package包/类
static Mono<VaultToken> augmentWithSelfLookup(WebClient webClient, VaultToken token) {

		Mono<Map<String, Object>> data = lookupSelf(webClient, token);

		return data.map(it -> {

			Boolean renewable = (Boolean) it.get("renewable");
			Number ttl = (Number) it.get("ttl");

			if (renewable != null && renewable) {
				return LoginToken.renewable(token.toCharArray(),
						LoginTokenAdapter.getLeaseDuration(ttl));
			}

			return LoginToken.of(token.toCharArray(),
					LoginTokenAdapter.getLeaseDuration(ttl));
		});
	}
 
开发者ID:spring-projects,项目名称:spring-vault,代码行数:19,代码来源:ReactiveLifecycleAwareSessionManager.java

示例8: lookupSelf

import org.springframework.web.reactive.function.client.WebClient; //导入依赖的package包/类
private static Mono<Map<String, Object>> lookupSelf(WebClient webClient,
		VaultToken token) {

	return webClient
			.get()
			.uri("auth/token/lookup-self")
			.headers(httpHeaders -> httpHeaders.putAll(VaultHttpHeaders.from(token)))
			.retrieve()
			.bodyToMono(VaultResponse.class)
			.map(it -> {

				Assert.state(it.getData() != null, "Token response is null");
				return it.getRequiredData();
			})
			.onErrorMap(
					WebClientResponseException.class,
					e -> {
						return new VaultTokenLookupException(String.format(
								"Token self-lookup failed: %s %s", e.getStatusCode(),
								VaultResponses.getError(e.getResponseBodyAsString())));
					});
}
 
开发者ID:spring-projects,项目名称:spring-vault,代码行数:23,代码来源:ReactiveLifecycleAwareSessionManager.java

示例9: justLoginRequestShouldLogin

import org.springframework.web.reactive.function.client.WebClient; //导入依赖的package包/类
@Test
public void justLoginRequestShouldLogin() {

	ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST,
			"/auth/cert/login");
	MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);
	response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
	response.setBody("{"
			+ "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
			+ "}");
	ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(
			Mono.just(response));

	WebClient webClient = WebClient.builder().clientConnector(connector).build();

	AuthenticationSteps steps = AuthenticationSteps.just(post("/auth/{path}/login",
			"cert").as(VaultResponse.class));

	StepVerifier.create(login(steps, webClient))
			.expectNext(VaultToken.of("my-token")).verifyComplete();
}
 
开发者ID:spring-projects,项目名称:spring-vault,代码行数:22,代码来源:AuthenticationStepsOperatorUnitTests.java

示例10: justLoginShouldFail

import org.springframework.web.reactive.function.client.WebClient; //导入依赖的package包/类
@Test
public void justLoginShouldFail() {

	ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.POST,
			"/auth/cert/login");
	MockClientHttpResponse response = new MockClientHttpResponse(
			HttpStatus.BAD_REQUEST);
	ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(
			Mono.just(response));

	WebClient webClient = WebClient.builder().clientConnector(connector).build();

	AuthenticationSteps steps = AuthenticationSteps.just(post("/auth/{path}/login",
			"cert").as(VaultResponse.class));

	StepVerifier.create(login(steps, webClient)).expectError().verify();
}
 
开发者ID:spring-projects,项目名称:spring-vault,代码行数:18,代码来源:AuthenticationStepsOperatorUnitTests.java

示例11: VaultRule

import org.springframework.web.reactive.function.client.WebClient; //导入依赖的package包/类
/**
 * Create a new {@link VaultRule} with the given {@link SslConfiguration} and
 * {@link VaultEndpoint}.
 *
 * @param sslConfiguration must not be {@literal null}.
 * @param vaultEndpoint must not be {@literal null}.
 */
public VaultRule(SslConfiguration sslConfiguration, VaultEndpoint vaultEndpoint) {

	Assert.notNull(sslConfiguration, "SslConfiguration must not be null");
	Assert.notNull(vaultEndpoint, "VaultEndpoint must not be null");

	RestTemplate restTemplate = TestRestTemplateFactory.create(sslConfiguration);
	WebClient webClient = TestWebClientFactory.create(sslConfiguration);

	VaultTemplate vaultTemplate = new VaultTemplate(
			TestRestTemplateFactory.TEST_VAULT_ENDPOINT,
			restTemplate.getRequestFactory(), new PreparingSessionManager());

	this.token = Settings.token();

	this.prepareVault = new PrepareVault(webClient,
			TestRestTemplateFactory.create(sslConfiguration), vaultTemplate);
	this.vaultEndpoint = vaultEndpoint;
}
 
开发者ID:spring-projects,项目名称:spring-vault,代码行数:26,代码来源:VaultRule.java

示例12: reactiveVaultSessionManager

import org.springframework.web.reactive.function.client.WebClient; //导入依赖的package包/类
/**
 * @return {@link ReactiveSessionManager} for reactive session use.
 * @see ReactiveSessionManager
 * @see ReactiveLifecycleAwareSessionManager
 */
@Bean
@ConditionalOnMissingBean
public ReactiveSessionManager reactiveVaultSessionManager(BeanFactory beanFactory,
		ObjectFactory<TaskSchedulerWrapper> asyncTaskExecutorFactory) {

	VaultTokenSupplier vaultTokenSupplier = beanFactory.getBean("vaultTokenSupplier",
			VaultTokenSupplier.class);

	if (vaultProperties.getConfig().getLifecycle().isEnabled()) {

		WebClient webClient = ReactiveVaultClients.createWebClient(vaultEndpoint,
				clientHttpConnector);
		return new ReactiveLifecycleAwareSessionManager(vaultTokenSupplier,
				asyncTaskExecutorFactory.getObject().getTaskScheduler(), webClient);
	}

	return CachingVaultTokenSupplier.of(vaultTokenSupplier);
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-vault,代码行数:24,代码来源:ReactiveVaultBootstrapConfiguration.java

示例13: multipleWebClientBuilders

import org.springframework.web.reactive.function.client.WebClient; //导入依赖的package包/类
@Test
public void multipleWebClientBuilders() {
	ConfigurableApplicationContext context = init(TwoWebClientBuilders.class);
	final Map<String, WebClient.Builder> webClientBuilders = context
			.getBeansOfType(WebClient.Builder.class);

	assertThat(webClientBuilders).hasSize(2);

	TwoWebClientBuilders.Two two = context.getBean(TwoWebClientBuilders.Two.class);

	assertThat(two.loadBalanced).isNotNull();
	assertLoadBalanced(two.loadBalanced);

	assertThat(two.nonLoadBalanced).isNotNull();
	assertThat(getFilters(two.nonLoadBalanced)).isNullOrEmpty();
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-commons,代码行数:17,代码来源:ReactiveLoadBalancerAutoConfigurationTests.java

示例14: hystrixStreamWorks

import org.springframework.web.reactive.function.client.WebClient; //导入依赖的package包/类
@Test
public void hystrixStreamWorks() {
	String url = "http://localhost:" + port;
	// you have to hit a Hystrix circuit breaker before the stream sends anything
	WebTestClient testClient = WebTestClient.bindToServer().baseUrl(url).build();
	testClient.get().uri("/").exchange().expectStatus().isOk();

	WebClient client = WebClient.create(url);

	Flux<String> result = client.get().uri(BASE_PATH + "/hystrix.stream")
			.accept(MediaType.TEXT_EVENT_STREAM)
			.exchange()
			.flatMapMany(res -> res.bodyToFlux(Map.class))
			.take(5)
			.filter(map -> "HystrixCommand".equals(map.get("type")))
			.map(map -> (String)map.get("type"));

	StepVerifier.create(result)
			.expectNext("HystrixCommand")
			.thenCancel()
			.verify();
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-netflix,代码行数:23,代码来源:HystrixWebfluxEndpointTests.java

示例15: sayhandler

import org.springframework.web.reactive.function.client.WebClient; //导入依赖的package包/类
@RequestMapping("/reactFuncEmps")
@ResponseBody
public Flux<Employee> sayhandler() {
           return WebClient.create().method(HttpMethod.GET)
        		   .uri("http://localhost:8908/listFluxEmps")
        		   .contentType(MediaType.APPLICATION_JSON_UTF8).retrieve().bodyToFlux(Employee.class);
 }
 
开发者ID:PacktPublishing,项目名称:Spring-5.0-Cookbook,代码行数:8,代码来源:ClientReactiveController.java


注:本文中的org.springframework.web.reactive.function.client.WebClient类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。