【问题标题】:Spring WebClient does not decode application/octet-stream into File objectSpring WebClient 不会将 application/octet-stream 解码为 File 对象
【发布时间】:2022-08-09 20:55:21
【问题描述】:

您好我正在使用 OpenAPI Generator Maven 插件生成一些 Java 客户端代码(使用 Spring WebClient 库)。我的规范的端点之一。返回二进制内容,例如:

\"schema\": {
  \"type\": \"string\",
  \"format\": \"binary\"
}

生成的代码使用 java.io.File 作为返回类型,例如:

public Mono<ResponseEntity<File>> downloadWithHttpInfo(String filename) throws WebClientResponseException {
    ParameterizedTypeReference<File> localVarReturnType = new ParameterizedTypeReference<File>() {};
    return downloadRequestCreation(filename).toEntity(localVarReturnType);
}

调用此生成的方法时,响应代码为 200(即来自服务器端的 OK),但我的客户端代码中出现以下错误:

org.springframework.web.reactive.function.UnsupportedMediaTypeException:
    Content type \'application/octet-stream\' not supported for bodyType=java.io.File

这来自 toEntity() 方法,它是 Spring WebClient 代码的一部分,而不是我的代码。

有没有办法解决这个问题? A:指示OpenAPI Generator Maven Plugin不要使用java.io.File类型而是使用Resource类型? B: 以某种方式让 WebClient 能够将 application/octet-stream 解码为java.io.File

    标签: java spring-webflux spring-webclient openapi-generator openapi-generator-maven-plugin


    【解决方案1】:

    找到解决方案:将以下选项添加到 OpenAPI Generator Maven 插件,然后再次生成代码,将 File 替换为 Resource

    <generatorName>java</generatorName>
    <library>webclient</library>
    <typeMappings>string+binary=Resource</typeMappings>
    <importMappings>Resource=org.springframework.core.io.Resource</importMappings>
    

    上面说的是当返回类型为string,格式为binary时,映射到Resource,对于Resource,导入为org.springframework.core.io.Resource。你去吧。

    【讨论】:

      【解决方案2】:

      我有完全相同的问题,但使用 Gradle 而不是 Maven。 以下是在 Gradle 中执行相同操作的语法:

      task generateClientSources(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask) {
          generatorName = 'java'
          // other configs ..
          configOptions = [
                  // other configs ..
                  library : 'webclient'
          ]
          typeMappings = [
                  File : 'Resource'
          ]
          importMappings = [
                  File : 'org.springframework.core.io.Resource'
          ]
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-12
        • 1970-01-01
        • 2014-06-08
        • 2014-11-25
        • 2018-10-27
        • 1970-01-01
        • 2010-12-28
        • 2023-03-22
        相关资源
        最近更新 更多