标签: spring-webclient

如何禁用 Java webflux webclient 请求中的安全证书检查

通过 webflux webclient 发出 post/get 请求时如何禁用 ssl 检查?

我正在使用的示例构建器代码:

WebClient webClient = WebClient.builder()
        .baseUrl("https://api.github.com")
        .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/vnd.github.v3+json")
        .defaultHeader(HttpHeaders.USER_AGENT, "Spring 5 WebClient")
        .build();
Run Code Online (Sandbox Code Playgroud)

在上面的代码中应该进行哪些更改才能使 ssl 验证错误?

java spring-boot spring-webflux spring-webclient

4
推荐指数
1
解决办法
2万
查看次数

使用 Spring WebClient 返回完整的响应

我有以下代码

public ClientResponse doGet(HttpServletRequest request, URI uri) {
    return webClient.get()
            .uri(uri.toASCIIString())
            .headers(headers -> headers.putAll(processRequest(request))
            .exchange()
            .block();
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试通过 RestController 返回此 ClientResponse 时,如下所示,

@GetMapping
@ResponseBody
public ClientResponse doGet(HttpServletRequest request) {
    ClientResponse node = service.doGet(request);
    return node;
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

org.springframework.http.converter.HttpMessageNotWritableException:找不到类型返回值的转换器:类org.springframework.web.reactive.function.client.DefaultClientResponse

基本上,我想要的最终目标是将实际响应返回给调用者 - 包括标头、正文、cookie等。

我正在考虑像下面这样使用 ResponseEntity 。

public ResponseEntity<JsonNode> doGet2(HttpServletRequest request, URI uri) {

    Mono<ClientResponse> clientResponse = webClient.get()
            .uri(uri.toASCIIString())
            .headers(headers -> headers.putAll(processRequest(request))
            .exchange();

    HttpHeaders headers = clientResponse.map(resp -> resp.headers().asHttpHeaders()).block();
    JsonNode body = clientResponse.flatMap(resp -> resp.bodyToMono(JsonNode.class)).block();

    ResponseEntity<JsonNode> jsonNode = ResponseEntity.ok().headers(headers).body(body);
    return jsonNode; …
Run Code Online (Sandbox Code Playgroud)

spring-boot spring-webclient spring5

4
推荐指数
1
解决办法
2万
查看次数

如何使用Spring WebClient进行同步调用?

Spring FrameworkRestTemplate文档中有注释:

\n
\n

注意:截至5.0此类处于维护模式,仅接受较小的\n更改请求和错误。请考虑使用org.springframework.web.reactive.client.WebClient具有更现代的 API 并支持同步、异步和流式传输的方案。

\n
\n

当我尝试使用WebClient并进行同步调用时,如下所示:

\n
@RestController\n@RequestMapping("/rating")\npublic class Controller {\n\n    @Autowired\n    private RestTemplate restTemplate;\n\n    @Autowired\n    private WebClient.Builder webClientBuilder;\n\n    @RequestMapping("/{userId}")\n    public UserRating getUserRating(@PathVariable("userId") String userId) {\n\n//      return restTemplate.getForObject("http://localhost:8083/ratingsdata/user/" + userId, UserRating.class);\n        return webClientBuilder.build()\n                .get().uri("http://localhost:8083/ratingsdata/user/" + userId)\n                .retrieve()\n                .bodyToMono(UserRating.class)\n                .block();\n\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

项目pom.xml:

\n
<?xml version="1.0" encoding="UTF-8"?>\n<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">\n    <modelVersion>4.0.0</modelVersion>\n    <parent>\n        <groupId>org.springframework.boot</groupId>\n        <artifactId>spring-boot-starter-parent</artifactId>\n        <version>2.4.0</version>\n        <relativePath/> <!-- lookup parent from repository -->\n    </parent>\n    <groupId>com.daren.tutorial.movie</groupId>\n    <artifactId>catalog</artifactId>\n    <version>0.0.1-SNAPSHOT</version>\n    <name>catalog</name>\n …
Run Code Online (Sandbox Code Playgroud)

java spring rest-client spring-boot spring-webclient

4
推荐指数
1
解决办法
5009
查看次数

如何在Reactor Netty HTTP客户端中设置TCP Keepalive?

我看到了

HttpClient.from(TcpClient.create().option(ChannelOption.SO_KEEPALIVE, true)) 
Run Code Online (Sandbox Code Playgroud)

from方法已被弃用。

目前我应该如何设置SO_KEEPALIVE使用HttpClient.create()

netty kotlin reactor-netty spring-webflux spring-webclient

4
推荐指数
1
解决办法
1902
查看次数

带有 ParameterizedTypeReference 的 Spring WebClient 不起作用

我有一个 Spring Boot 应用程序,我正在使用 WebClient 向 API 发出请求,该 API 返回以下格式,其中{"results": {...}}字段中的对象results可以采用多种不同的格式。我创建了以下类来存储 API 响应。

@Data
@Jacksonized
@Builder
public class ApiResponse<T> {
    private T results;
}
Run Code Online (Sandbox Code Playgroud)

当我调用以下方法时:

public MyResClass makeApiCall(String URI) {
    ApiResponse<MyResClass> response = webClient.get()
                    .uri(URI)
                    .accept(MediaType.APPLICATION_JSON)
                    .retrieve()
                    .bodyToMono(new ParameterizedTypeReference<ApiResponse<MyResClass>>() {})
                    .block();

    return response.getResults();
}
Run Code Online (Sandbox Code Playgroud)

抛出ajava.lang.ClassCastException并显示以下消息:“java.util.LinkedHashMap 类无法转换为 MyResClass 类”

java spring jackson spring-boot spring-webclient

4
推荐指数
1
解决办法
6336
查看次数

Spring-Boot WebClient block() 方法返回错误 java.lang.IllegalStateException

我正在尝试使用 Spring WebFlux WebClient获取值(字符串) (使用 SpringBoot 版本 2.4.5)

\n
@GetMapping("/test")\npublic Mono<String> getData(){\n    WebClient webClient = WebClient.create("http://localhost:9999");\n    Mono<String> stringMono = webClient.get()\n            .uri("/some/thing")\n            .retrieve()\n            .bodyToMono(String.class);\n    stringMono.subscribe( System.out::println);\n    System.out.println("Value : " + stringMono.block()); // this doesn\'t work,  expecting to return ResponseBody as "Hello World" ,\n    return stringMono;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

但低于错误

\n
2021-05-11 20:02:15.521 ERROR 55613 --- [ctor-http-nio-2] a.w.r.e.AbstractErrorWebExceptionHandler : [19114471-1]  500 Server Error for HTTP GET "/test"\njava.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-2\n    at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:83) ~[reactor-core-3.4.3.jar:3.4.3]\n    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: \nError …
Run Code Online (Sandbox Code Playgroud)

spring-boot spring-webflux spring-webclient

4
推荐指数
1
解决办法
1万
查看次数

如何使用 spring-security-oauth2 和 WebClient 自定义 OAuth2 令牌请求的授权标头?

我正在尝试通过 WebClient 调用升级到 spring security 5.5.1。我发现 oauth2 clientId机密现在是 URL 编码的AbstractWebClientReactiveOAuth2AccessTokenResponseClient,但我的令牌提供程序不支持这一点(例如,如果机密包含字符,则+仅当它作为+not as发送时才有效%2B)。我知道这被视为spring-security 方面的错误修复),但我无法让令牌提供者轻松更改其行为。

所以我试图找到一种方法来解决这个问题。

关于如何自定义访问令牌请求的[文档](https://docs.spring.io/spring-security/site/docs/current/reference/html5/#customizing-the-access-token-request )没有当您使用 WebClient 配置时似乎适用(这是我的情况)。

为了删除 clientid/secret 编码,我必须扩展和复制大部分现有代码以AbstractWebClientReactiveOAuth2AccessTokenResponseClient进行自定义,WebClientReactiveClientCredentialsTokenResponseClient因为其中大部分具有私有/默认可见性。我在 spring-security 项目的一个增强问题中追踪到了这一点。

是否有更简单的方法来自定义令牌请求的授权标头,以跳过 url 编码?

spring-security spring-security-oauth2 spring-webflux spring-webclient

4
推荐指数
1
解决办法
2919
查看次数

Spring RestTemplate 与 WebClient 的同步请求

抱歉,如果之前有人问过这个问题,但我没有找到匹配的问题。

我有一个对其他服务执行 api 调用的应用程序。我正在考虑按照 Spring 的建议使用WebClientover 。RestTemplate我只执行同步 HTTP 调用。

我知道WebClient设计时考虑了响应式方法,但从理论上讲:可以WebClient仅用于阻止调用吗?我担心的是我必须.block()每次通话才能获取数据。所以我的问题是:

  1. 使用它的安全性如何.block()?通常可以阻止其中的线程吗WebClient
  2. 阻止调用背后的机制是否与WebClient类似RestTemplate
  3. 性能是否有可能比我只使用时更差RestTemplate

提前致谢!

java spring resttemplate spring-webflux spring-webclient

4
推荐指数
1
解决办法
5645
查看次数

如何在 WebClient 单元测试中使用 MockWebServer 模拟错误响应

我正在为使用 WebClient 调用 REST 端点的方法编写单元测试。使用 MockWebServer,我能够覆盖成功响应的代码,但我无法找到任何方法来模拟错误响应,以便单元测试中也覆盖与错误处理相关的代码。

源类:

@Service
@Slf4j
public class EmployeeService {

   private final WebClient webClient;
   private final PaymentServiceConfiguration paymentServiceConfiguration;
   
   public EmployeeService(WebClient webClient, PaymentServiceConfiguration paymentServiceConfiguration){
      this.webClient = webClient;
      this.paymentServiceConfiguration= paymentServiceConfiguration;

   }

   public Mono<PaymentDataResponse> getPaymentInfo(PaymentDataRequest paymentDataRequest){
      return webClient
             .post()
             .uri(paymentServiceConfiguration.getBaseUri() + "/payment")
             .body(Mono.just(paymentDataRequest, PaymentDataRequest.class)
             .retrieve()
             .onStatus(HttpStatus::isError, this.handleErrorResponse)
             .bodyToMono(PaymentDataResponse.class)
             .doOnError((throwable)-> {
                 log.error("Exception in getPaymentInfo method. Message {}", throwable.getMessage());
                 throw(Exceptions.propagate(throwable));
             });

   }

   private Mono<? extends Throwable> handleErrorResponse(ClientResponse clientResponse){
      Mono<String> errorMessage = clientResponse.bodyToMono(String.class);
      return errorMessage.flatMap((message) -> {
         log.error("Error response code is: {}, and …
Run Code Online (Sandbox Code Playgroud)

junit mockito spring-webflux spring-webclient

4
推荐指数
1
解决办法
1万
查看次数

Web 客户端在未找到响应时返回 Optional.empty()

当我从服务器收到 404(未找到)时,我试图WebClient返回一个Optional.empty()。但相反,我得到了一个 OptionalUser对象,所有属性都设置为 null。

我错过了什么?

@Override
public Optional<User> getUser(Username username) {
    return webClient
            .get()
            .uri(buildUrl(username))
            .retrieve()
            .onStatus(HttpStatus.NOT_FOUND::equals, response -> Mono.empty())
            .onStatus(HttpStatus::is4xxClientError, response -> createError(response, CLIENTERROR))
            .onStatus(HttpStatus::is5xxServerError, response -> createError(response, SERVRERROR))
            .bodyToMono(User.class)
            .blockOptional();
}
Run Code Online (Sandbox Code Playgroud)

java spring-webclient

3
推荐指数
1
解决办法
1454
查看次数