Search code examples
javaspring-webfluxspring-webclientopenapi-generatoropenapi-generator-maven-plugin

Spring WebClient does not decode application/octet-stream into File object


Hi I am using OpenAPI Generator Maven Plugin to generate some Java Client code (using Spring WebClient library). One of the endpoints of my spec. returns binary content, like:

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

The generated code uses java.io.File as the return type for that, like:

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

When calling this generated method, the response code was 200 (i.e. OK from the server side), but I got the following error in my client code:

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

This came from the toEntity() method, which is part of the Spring WebClient code instead of my code.

Is there a way to workaround this? A: Instruct OpenAPI Generator Maven Plugin not to use java.io.File type but use Resource type? B: Somehow make WebClient able to decode application/octet-stream into java.io.File?


Solution

  • Found a solution: add the following options to the OpenAPI Generator Maven Plugin then generate the code again, which would replace File to Resource

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

    The above is saying when the return type is string and the format is binary, map it to Resource and for Resource import it as org.springframework.core.io.Resource. There you go.