Skip to content

WebClient: Explicit Content-Type application/octet-stream is overwritten  #33303

@othi

Description

@othi

Affected version: 6.1.11

The API I'm consuming requires the Content-Type header to be application/octet-stream for certain binary payloads.

The Content-Type is set explicitly using RequestBodySpec.contentType() but it is later overwritten in this method:

private static MediaType getResourceMediaType(
@Nullable MediaType mediaType, Resource resource, Map<String, Object> hints) {
if (mediaType != null && mediaType.isConcrete() && !mediaType.equals(MediaType.APPLICATION_OCTET_STREAM)) {
return mediaType;
}
mediaType = MediaTypeFactory.getMediaType(resource).orElse(MediaType.APPLICATION_OCTET_STREAM);
if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
logger.debug(Hints.getLogPrefix(hints) + "Resource associated with '" + mediaType + "'");
}
return mediaType;
}

This is unintuitive behaviour and not configurable. To circumvent this, I have to rename the file to an extension not present in spring-web/src/main/resources/org/springframework/http/mime.types so my explicitly set header is respected.

To reproduce, here is a function that sets the content type of the request:

    public void test() throws IOException {
        File f = File.createTempFile("test", ".pdf");

        WebClient webClient = WebClient.create();
        RequestBodySpec builder = webClient.method(HttpMethod.POST).uri("http://localhost:12458");
        builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
        builder.body(BodyInserters.fromValue(new FileSystemResource(f)));
        builder.retrieve().toBodilessEntity().block();
    }

Resulting request using netcat:

me@dev:~$ nc -l 12458
POST / HTTP/1.1
accept-encoding: gzip
user-agent: ReactorNetty/1.1.9
host: localhost:12458
accept: */*
Content-Type: application/pdf   <---------
content-length: 0

Expected result:

Content-Type: application/octet-stream

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    in: webIssues in web modules (web, webmvc, webflux, websocket)status: declinedA suggestion or change that we don't feel we should currently apply

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions