标签: spring-webclient

Webclient maven 依赖错误

我尝试使用“ createNoClassDefFoundError ”创建 WebClient 实例。尝试了 builder() 但仍然是同样的事情。

请告诉我我添加的依赖项有什么问题以及如何解决这个问题。

             webClient = WebClient.create(url)
                                .post()
                                .uri(uri)
                                .contentType(MediaType.APPLICATION_JSON)
                                .body(BodyInserters.fromMultipartData(map))
                                .retrieve()
                                .bodyToMono(Object.class)
                                .block()
                                .toString()
Run Code Online (Sandbox Code Playgroud)

我添加的依赖项是

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-core</artifactId>
        </dependency>
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪:

Exception in Async java.lang.NoClassDefFoundError: reactor/netty/http/client/HttpClient

java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError: reactor/netty/http/client/HttpClient
        
        at org.springframework.http.client.reactive.ReactorClientHttpConnector.<clinit>(ReactorClientHttpConnector.java:44)
        
        at org.springframework.web.reactive.function.client.DefaultWebClientBuilder.initExchangeFunction(DefaultWebClientBuilder.java:226)
        
        at org.springframework.web.reactive.function.client.DefaultWebClientBuilder.build(DefaultWebClientBuilder.java:207)
        
        at org.springframework.web.reactive.function.client.WebClient.create(WebClient.java:144)

Caused by: java.lang.NoClassDefFoundError: reactor/netty/http/client/HttpClient
        
        ... 16 common frames omitted

Caused by: java.lang.ClassNotFoundException: reactor.netty.http.client.HttpClient
        
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
        
        at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
        
        at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:92)
        
        at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
        
        ... 16 common frames omitted

Run Code Online (Sandbox Code Playgroud)

maven spring-boot spring-webflux spring-webclient

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

使用 webclient webflux 将文件发布到接受 APPLICATION_OCTET_STREAM 的 API

我想使用 Webflux Web 客户端将文件上传到 Rest api。接受文件的 API 具有内容类型,APPLICATION_OCTET_STREAM我如何使用 spring 来做到这一点WebClient

我怎样才能将下面的curl转换为WebClient请求?

curl -i -X POST --header "Content-Type:application/octet-stream" --header --data-binary @myfile.pdf  https://some-host/some-url
Run Code Online (Sandbox Code Playgroud)

注意- 我不期望有很大的文件

spring-boot spring-webflux spring-webclient

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

如何在 Spring Webflux webclient 中添加带有 HttpOnly 和 Secure 标志的 cookie?

当前在 SpringWebFlux Web 客户端中设置 cookie,我手动添加带有等号的 cookie,例如 name1=value;name2=value;name3-value 并将其添加到带有 Cookie 键的标头中。

webclient.get().header("Cookie",name1=value;name2=value;name3-value);
Run Code Online (Sandbox Code Playgroud)

但我不知道如何为添加的这些 cookie 添加HttpOnly 或 Secure 标志。请让我知道如何在使用 spring webclient 对 Https URL 进行 REST 调用时添加这些标志?我找不到添加这些标志的方法。如果通过 HTTPS 连接,是否强制添加这些标志?

java spring-boot spring-webflux spring-webclient

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

带有 get() 和 requestBody 的 WebTestClient 不可用

我有一个应用程序,其中一个 api 是使用 Get 方法定义的。它还需要请求正文,然后将其映射到 POJO。我正在尝试使用 webTestClient 测试该控制器。但我没有看到使用 get() 方法发送请求正文的选项。不确定我是否以正确的方式定义我的 webTestClient。

我的控制器看起来像:

@GetMapping
public Flux<ResponseBody> getAllResources(@RequestBody Resource resource) {
//related code here...
}
Run Code Online (Sandbox Code Playgroud)

我的测试方法:

@Test
public void myTest() {

webClient.get()
.uri("uri_path")
.header("Content-Type", "application/json")
.accept("application/json")
.exchange()
.expectedStatus.is2xxxSuccessful();
}
Run Code Online (Sandbox Code Playgroud)

我在想,既然控制器允许通过 get 调用将对象绑定到 POJO,那么应该有某种方法使用 webTestClient 来测试它。

java rest integration-testing spring-webclient webtestclient

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

如何将 Spring Webclient 的内容类型设置为“application/json-patch+json”

我正在尝试向另一个接受内容类型“application/json-patch+json”的 API 发出补丁休息请求。我正在使用 Spring 的网络客户端,但我无法让它工作。我不断收到“415 不支持的媒体类型”

我已经尝试过以下方法;

WebClient webClient = WebClient.create(baseUrl);
Mono<ClientResponse> response = webClient.patch()
  .uri(updateVmfExecutionApi, uuid)
  .header("Content-Type", "application/json-patch+json")
  .body(BodyInserters.fromFormData("lastKnownState", state))
  .exchange();
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

WebClient webClient = WebClient.create(baseUrl);
    Mono<ClientResponse> response = webClient.patch()
      .uri(updateVmfExecutionApi, uuid)
      .contentType(MediaType.valueOf("application/json-patch+json"))
      .body(BodyInserters.fromFormData("lastKnownState", state))
      .exchange();
Run Code Online (Sandbox Code Playgroud)

对于这两种情况,我都会看到以下错误;

 {"timestamp":"2020-09-17T20:50:40.818+0000","status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Unsupported Media Type","trace":"org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported\n\tat org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:215)\n\tat org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:421)\n\tat org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:367)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getHandlerInternal(RequestMappingHandlerMapping.java:449)
Run Code Online (Sandbox Code Playgroud)

似乎它更改为 'application/x-www-form-urlencoded;charset=UTF-8' 是否可以为此内容类型使用 webclient?

java spring spring-boot spring-webflux spring-webclient

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

Spring WebClient:Retry.backoff 的默认乘数是多少?

我试图了解 Spring WebClient Retry.backoff 方法的指数退避策略的默认乘数。并且这个可以配置吗?我找不到这方面的文档。

https://projectreactor.io/docs/core/release/api/reactor/util/retry/Retry.html#backoff-long-java.time.Duration-

版本: reactor-netty 0.9.12.RELEASE

spring reactor-netty spring-webclient

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

Spring WebFlux switchIfEmpty 返回不同类型

public Mono<ServerResponse> getMessage(ServerRequest request) {
    //this call returns Mono<ApiClientResponse>
    return apiClient.hystrixWrappedGetMessages(request.headers().asHttpHeaders(), request.queryParams())
            .switchIfEmpty(/* Here */)
}
Run Code Online (Sandbox Code Playgroud)

请原谅代码稍微不完整,当我遇到这个问题时,我正在重组它。要点是 /* Here */ 在调用中switchIfEmpty(),编译器强制使用类型Mono<ApiClientResponse>,但是当hystrixWrappedGetMessages()返回时Mono.empty()我想通过返回 204 来处理它Mono<ServerResponse>,否则我想返回 200。我怎样才能做到这一点?

理想情况下,我可以在地图调用中检查它是否是 Mono.empty() ,但如果它是空的 Mono,它似乎不会输入地图。考虑过使用可选选项,但它们似乎与 Monos 不能很好地配合。

java reactive-programming reactor-netty spring-webflux spring-webclient

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

如何在Reactor中进行分页?

我向第三方 Web 服务重复发出分页 WebClient 请求。我现在的实现可以工作,但正在阻塞

到目前为止我的实现:

var elementsPerPage = 10;
Flux
    .generate(
        () -> 0,
        (pageIndex, emitter) -> {
            BlahServiceResponse blahServiceResponse =
                webClient
                    .get()
                    .uri("/blah?pageIndex={pageIndex}", pageIndex)
                    .retrieve()
                    .bodyToMono(BlahServiceResponse.class)
                    .block(); // Yuck!!!
            if (blahServiceResponse.getStudents().size() > 0) {
                emitter.next(blahServiceResponse);
            } else {
                emitter.complete();
            }
            return pageIndex + elementsPerPage;
        }
    )
    .subscribe(System.out::println); // Replace me with actual logic
Run Code Online (Sandbox Code Playgroud)

出于可以理解的原因,如果上面的代码更改为以下内容,则会引发“IllegalStateException:生成器没有调用任何 SynchronousSink 方法”异常:

webClient
    .get()
    ...
    .bodyToMono(BlahServiceResponse.class)
    .subscribe(emitter::next);
Run Code Online (Sandbox Code Playgroud)

所以我开始寻找一个异步接收器并意识到它是 Flux|MonoSink。但据我所知,Flux 中没有构建器方法支持使用 Flux|MonoSink 生成有状态元素。

我是否遗漏了一些东西,是否有更优雅的方法?

java spring project-reactor spring-webflux spring-webclient

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

嵌套异常是 web.reactive.function.UnsupportedMediaTypeException:bodyType 不支持内容类型“text/html;charset=utf-8”

创建了一个 REST Web 服务(服务 1),它尝试使用另一个服务(服务 2),该服务返回 Content-Type =“text/html;charset=utf-8”

我的 WebClient 代码使用另一个服务:

ublic <T, N> N invokeService(String endPointUrl, HttpMethod httpMethod, HttpHeaders headers, T requestPayload,
            Class<T> requestPlayLoadClass, Class<N> serviceResponseClass) {
    UriSpec<RequestBodySpec> uriSpec = webclient.method(httpMethod);
    RequestBodySpec bodySpec = uriSpec.uri(endPointUrl);
    RequestHeadersSpec<?> headersSpec = buildRequest(headers, requestPayload, requestPlayLoadClass, bodySpec);

    Mono<N> res = headersSpec.retrieve()
                .onStatus(HttpStatus::is4xxClientError, clientResponse -> handle4xxError(clientResponse))
                .onStatus(HttpStatus::is5xxServerError, clientResponse -> handle5xxError(clientResponse))
                .bodyToMono(serviceResponseClass);

    return res.block();

}

private <T> RequestHeadersSpec<?> buildRequest(HttpHeaders headers, T requestPayload, Class<T> requestPlayLoadClass,
            RequestBodySpec bodySpec) {
        RequestHeadersSpec<?> headersSpec = bodySpec.headers(clientHeaders -> clientHeaders.addAll(headers));
        if (requestPayload != …
Run Code Online (Sandbox Code Playgroud)

spring-webclient

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

如何以非阻塞方式从 WebClient bodyToMono 或 toEntity 获取对象

我是 Spring WebClient 的新手。我有以下方法使用 WebClient 调用端点,并且我需要从此方法返回 ResponseEntity。我知道我可以 call block(),但是我是否可以以非阻塞的方式做到这一点?即使我可以 return Mono,调用方法仍然需要解开它并获取 ResponseEntity ,调用方法如何执行,调用block

public ResponseEntity getData() {

    Mono<ResponseEntity<String>> entityMono = webClient.post()
                                                       .uri(url)
                                                       .body(BodyInserters.fromValue(aString))
                                                       .retrieve()
                                                       .toEntity(String.class);

     // what do I need to do here so that I can return ResponseEntity non-blocking

}
Run Code Online (Sandbox Code Playgroud)

java spring-webflux spring-webclient

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