Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot RestController - PostMapping - Process Request Body as InputStream [duplicate]

Is there an easy way to process the body of a POST HTTP request as an InputStream when using PostMapping in a Spring Boot RestController?

It is quite simple to accept file uploads from Multipart HTTP POST requests as MultipartFile instances, but I would like to be able to simply post binary content to an HTTP endpoint and process this as an InputStream.

Is this possible with Spring Boot?

For example with the following Postman POST:

enter image description here

like image 380
Attila Avatar asked Jan 18 '20 11:01

Attila


Video Answer


2 Answers

I know two possible ways

Take HttpEntity

@PostMapping
public ResponseEntity<String> post(HttpEntity<byte[]> requestEntity) {
    return ResponseEntity.ok(new String(requestEntity.getBody()));
}

Take whole Request

@PostMapping
public ResponseEntity<String> post(HttpServletRequest request) {
    request.getInputStream();
}
like image 104
Matthias Avatar answered Oct 21 '22 15:10

Matthias


If you just have an InputStream parameter on your method then you get the request body.

@RequestMapping(method = RequestMethod.PUT)
public ResponseEntity<Void> put(InputStream is) {
    // Do something
    return ResponseEntity.ok();
}

This is with Spring Boot 2.4.1.

like image 40
Matthew Buckett Avatar answered Oct 21 '22 15:10

Matthew Buckett