springboot返回Byte字节

在Spring Boot中,可以使用`ResponseEntity`类来返回字节流。以下是一个简单的示例:

  1. 首先,创建一个控制器类,如`ByteController`:

```java

import org.springframework.http.MediaType;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class ByteController {

@GetMapping(value = "/return-bytes", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)

public ResponseEntity<byte[]> returnBytes() {

// 构造字节流

byte[] bytes = "Hello, World!".getBytes();

// 返回字节流

return ResponseEntity.ok().body(bytes);

}

}

```

  1. 这个示例中,使用`@GetMapping`注解来定义一个GET请求的处理方法。`produces`属性设置为`application/octet-stream`,表示该方法返回的是字节流。

  2. `ResponseEntity`类用于封装HTTP响应的状态码、头信息和响应体。我们可以使用`ResponseEntity.ok()`方法创建一个状态码为200 OK的响应实体,然后使用`body()`方法设置响应体为字节流。

  3. 当客户端发送一个GET请求到`/return-bytes`时,Spring Boot会自动将`returnBytes`方法的返回值作为响应体发送给客户端。

相关推荐
石头5306 小时前
Kubernetes监控全栈解决方案:从零搭建Prometheus+Grafana监控体系
linux
ha20428941946 小时前
Linux操作系统学习记录之---TcpSocket
linux·网络·c++·学习
AOwhisky6 小时前
Linux逻辑卷管理:从“固定隔间”到“弹性存储池”的智慧
linux·运维·服务器
BD_Marathon7 小时前
配置文件分类
spring boot
M***Z2107 小时前
springboot中配置logback-spring.xml
spring boot·spring·logback
C Yu小白8 小时前
Linux系统调用与文件操作详解
linux·运维·服务器
ZFB00018 小时前
【麒麟桌面系统】V10-SP1 2503 系统知识——常见用户组简介
linux·运维·kylin
f***28148 小时前
Springboot中使用Elasticsearch(部署+使用+讲解 最完整)
spring boot·elasticsearch·jenkins
EndingCoder8 小时前
类的继承和多态
linux·运维·前端·javascript·ubuntu·typescript
小毅&Nora8 小时前
【后端】【SpringBoot】① 源码解析:从启动到优雅关闭
spring boot·后端·优雅关闭