Skip to main content

On This Page

How to Set Content-Length Header in ResponseEntity in Spring MVC

2 min read
Share

These articles are AI-generated summaries. Please check the original sources for full details.

How to Set Content-Length Header in ResponseEntity in Spring MVC

Spring MVC applications often use the ResponseEntity class to send HTTP responses, with Spring typically managing headers automatically. However, accurately setting the Content-Length header is crucial for scenarios like file downloads where clients need to verify completeness or track progress. Explicit configuration only makes sense when the response size is known in advance.

The Content-Length header specifies the exact size of the HTTP response body in bytes, ensuring accurate data transfer, while omitting it often results in chunked transfer encoding suitable for streaming data. Incorrect Content-Length values can lead to truncated responses or client errors.

Key Insights

  • Content-Length and Transfer-Encoding: chunked are mutually exclusive: HTTP specification.
  • Filesize verification: Accurate Content-Length enables clients to verify downloaded files, boosting reliability.
  • ResponseEntity API: Using ResponseEntity.ok().contentLength() is the preferred method for clarity.

Working Example

@GetMapping("/hello")
public ResponseEntity<String> hello() {
String body = "Hello Spring MVC!";
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
return ResponseEntity.ok()
.contentLength(bytes.length)
.body(body);
}
@GetMapping("/download")
public ResponseEntity<Resource> download() throws IOException {
Path filePath = Paths.get("example.pdf"); // For tests, this file should exist
Resource resource = new UrlResource(filePath.toUri());
long fileSize = Files.size(filePath);
return ResponseEntity.ok()
.contentLength(fileSize)
.contentType(MediaType.APPLICATION_PDF)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"example.pdf\"")
.body(resource);
}

Practical Applications

  • File Download Service: A video streaming platform uses explicit Content-Length for downloads, ensuring accurate file transfer and progress indication for users.
  • Pitfall: Setting Content-Length on a streaming response will likely cause a client-side error due to inconsistent data size expectations.

References:

Continue reading

Next article

Inside Claude Code Creator Boris Cherny’s Development Workflow

Related Content