通过 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 验证错误?
我有以下代码
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 FrameworkRestTemplate文档中有注释:
\n\n注意:截至
\n5.0此类处于维护模式,仅接受较小的\n更改请求和错误。请考虑使用org.springframework.web.reactive.client.WebClient具有更现代的 API 并支持同步、异步和流式传输的方案。
当我尝试使用WebClient并进行同步调用时,如下所示:
@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}\nRun 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) 我看到了
HttpClient.from(TcpClient.create().option(ChannelOption.SO_KEEPALIVE, true))
Run Code Online (Sandbox Code Playgroud)
from方法已被弃用。
目前我应该如何设置SO_KEEPALIVE使用HttpClient.create()?
我有一个 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 类”
我正在尝试使用 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}\nRun Code Online (Sandbox Code Playgroud)\n但低于错误
\n2021-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) 我正在尝试通过 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
抱歉,如果之前有人问过这个问题,但我没有找到匹配的问题。
我有一个对其他服务执行 api 调用的应用程序。我正在考虑按照 Spring 的建议使用WebClientover 。RestTemplate我只执行同步 HTTP 调用。
我知道WebClient设计时考虑了响应式方法,但从理论上讲:可以WebClient仅用于阻止调用吗?我担心的是我必须.block()每次通话才能获取数据。所以我的问题是:
.block()?通常可以阻止其中的线程吗WebClient?WebClient类似RestTemplate?RestTemplate?提前致谢!
我正在为使用 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) 当我从服务器收到 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) spring-webclient ×10
java ×5
spring-boot ×5
spring ×3
jackson ×1
junit ×1
kotlin ×1
mockito ×1
netty ×1
rest-client ×1
resttemplate ×1
spring5 ×1