java / intermediate
Snippet
Flexible API Responses with ResponseEntity
ResponseEntity provides complete control over the HTTP response, including the status code, headers, and body. It is essential for advanced scenarios like file downloads or custom header manipulation.
snippet.java
1
2
3
4
5
6
7
8
9
@GetMapping("/download")public ResponseEntity<byte[]> downloadFile() {byte[] content = fileService.getFileBytes();return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"report.pdf\"").contentType(MediaType.APPLICATION_PDF).contentLength(content.length).body(content);}
spring
Breakdown
1
ResponseEntity.ok()
A static builder method for a response with HTTP status 200 (OK).
2
HttpHeaders.CONTENT_DISPOSITION
Standard header used to suggest a filename for the browser's 'Save As' dialog.
3
body(content)
Sets the payload of the response, in this case, a byte array for a PDF file.