Spring Boot 发送接收 POST 流请求 - 文件上传下载
在 Spring Boot 中发送和接收 POST 流请求可以使用以下方法:
- 发送 POST 流请求
RestTemplate restTemplate = new RestTemplate();
String url = 'http://localhost:8080/api/post';
InputStream stream = new FileInputStream(new File('file.txt'));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
HttpEntity<byte[]> requestEntity = new HttpEntity<>(IOUtils.toByteArray(stream), headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
上述代码中,我们使用了 RestTemplate 发送了一个 POST 请求,请求的内容是一个文件的流。我们使用 HttpHeaders 来设置请求头,将请求的内容类型设置为 MediaType.APPLICATION_OCTET_STREAM,表示请求的内容是一个二进制流。然后,我们将文件的流转换为 byte 数组,并使用 HttpEntity 将请求的内容包装起来。最后,我们执行 POST 请求,并将响应的结果转换为 String 类型。
- 接收 POST 流请求
@PostMapping(value = '/api/post', consumes = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<?> handlePostRequest(@RequestBody byte[] bytes) {
try (InputStream stream = new ByteArrayInputStream(bytes)) {
// 处理 POST 请求的流
return ResponseEntity.ok('Received the POST request');
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body('Error handling the POST request');
}
}
上述代码中,我们使用 @PostMapping 注解来声明一个 POST 请求处理方法,consumes 属性表示该方法可以处理的请求内容类型,这里我们设置为 MediaType.APPLICATION_OCTET_STREAM_VALUE,表示该方法可以处理二进制流类型的请求。在方法体中,我们将接收到的请求内容转换为字节数组,并使用 InputStream 将字节数组转换为输入流,然后对输入流进行处理即可。最后,我们返回一个 ResponseEntity 响应对象,表示处理结果。如果处理过程中出现异常,我们返回一个 500 错误响应。
原文地址: https://www.cveoy.top/t/topic/nmHZ 著作权归作者所有。请勿转载和采集!