本文整理汇总了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;
}
示例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)));
}
示例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;
});
}
示例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();
}
示例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()));
}
}
示例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));
}
示例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));
});
}
示例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())));
});
}
示例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();
}
示例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();
}
示例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;
}
示例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);
}
示例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();
}
示例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);
}