spring-boot - 如何在spring webflux中发送URL编码数据

标签 spring-boot spring-webflux

我正在编写一个 Spring 5 Web 应用程序,我的要求是获取 urlencoded 表单并作为响应发送 url 编码响应

这是路由器功能代码

@Configuration
public class AppRoute {

  @Bean
  public RouterFunction<ServerResponse> route(FormHandler formHandler) {

    return RouterFunctions.route()
           // .GET("/form", formHandler::sampleForm)
           // .POST("/form", accept(MediaType.APPLICATION_FORM_URLENCODED), formHandler::displayFormData)
            .POST("/formnew", accept(MediaType.APPLICATION_FORM_URLENCODED).and(contentType(MediaType.APPLICATION_FORM_URLENCODED)), formHandler::newForm)
            .build();
  }
}

这是我的处理程序代码

public Mono<ServerResponse> newForm(ServerRequest request) {
    Mono<MultiValueMap<String, String>> formData = request.formData();
    MultiValueMap<String, String> newFormData = new LinkedMultiValueMap<String, String>();

    formData.subscribe(p -> newFormData.putAll(p));
    newFormData.add("status", "success");

    return ServerResponse.ok().contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .body(fromObject(newFormData));
}

这是我收到的错误

2020-04-07 02:37:33.329 DEBUG 38688 --- [ctor-http-nio-3] org.springframework.web.HttpLogging : [07467aa5] Resolved [UnsupportedMediaTypeException: Content type 'application/x-www-form-urlencoded' not supported for bodyType=org.springframework.util.LinkedMultiValueMap] for HTTP POST /formnew

这里出了什么问题。我找不到任何方法来写回 url 编码的响应。 谁能指出问题出在哪里。

最佳答案

尝试将代码重构为函数式风格:

public Mono<ServerResponse> newForm(ServerRequest request) {
    Mono<DataBuffer> resultMono = request.formData()
        .map(formData -> new LinkedMultiValueMap(formData))
        .doOnNext(newFormData -> newFormData.add("status", "success"))
        .map(linkedMultiValueMap -> createBody(linkedMultiValueMap));

    return ServerResponse.ok().contentType(MediaType.APPLICATION_FORM_URLENCODED)
        .body(BodyInserters.fromDataBuffers(resultMono));


}

private DataBuffer createBody(MultiValueMap multiValueMap) {
    try {
        DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
        return factory.wrap(ByteBuffer.wrap(objectMapper.writeValueAsString(multiValueMap).getBytes(StandardCharsets.UTF_8)));
    } catch (JsonProcessingException e) {
        throw new IllegalArgumentException("incorrect body");
    }
}

关于spring-boot - 如何在spring webflux中发送URL编码数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61077057/

相关文章:

java - 如何在 Spring Boot JPA 中连接到多个数据库?

spring-boot - Spring Boot Rest Controller API 不返回 json

java - Spring Rest Docs 片段模板被忽略

postgresql - Spring-Boot 不适用于 Flyway

spring - 在请求写入完成之前,WebClient 不会读取响应。

spring-boot - Spring Boot 中的 Jetty 自定义格式日志模式

java - Spring Bean 验证给出 ConstraintDeclarationException

java - Spring MVC(异步)与 Spring WebFlux

java - Spring Webflux 不尊重数据库名称 MongoDB 的配置

java - Spring WebFlux 中的同步方法?