Skip to content

Resolved HttpEntity Controller argument does not reflect mutated HTTP headers #36298

@zelite

Description

@zelite

When sending a post request to a spring controller as application/x-www-form-urlencoded, if the parameter has a space encoded as %20, spring modifies the encoding to "+" but does not modify the content-length header.
This results in having a request entity where the content-lenght header does not match the body.

Here an example controller:

@RestController
public class ContentLengthController {
    @RequestMapping(
            value = "**",
            consumes = {"*/*", "application/*"},
            produces = "*/*",
            method = {GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE})
    public ResponseEntity<String> handleAll(RequestEntity<byte[]> request){
        byte[] body = request.getBody();
        long actualLength = body != null ? body.length : 0;
        long headerLength = request.getHeaders().getContentLength();

        String jsonResponse = String.format(
                "{\"actualLength\":%d,\"headerLength\":%d,\"match\":%b}",
                actualLength,
                headerLength,
                actualLength == headerLength
        );
        return ResponseEntity.ok(jsonResponse);
    }

}

And here an example test:

@SpringBootTest
@AutoConfigureMockMvc
class DemoApplicationTests {

	@Autowired
	private MockMvc mockMvc;

	@Test
	void contextLoads() {
	}

	@Test
	void testContentLengthMatch() throws Exception {

		mockMvc.perform(post("/test")
						.contentType(MediaType.APPLICATION_FORM_URLENCODED)
						.content("key=foo%20bar")
				)
				.andExpect(status().isOk())
				.andExpect(jsonPath("$.match").value(true));

	}

}

Either the body should not be modified, or the content length should have been adjusted accordingly.

The full example project can be found here: https://github.com/zelite/demo/tree/main

This Ticket seems related: #32471 but I do not see the modified header inside the RestController.

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)status: backportedAn issue that has been backported to maintenance branchestype: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions