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`方法的返回值作为响应体发送给客户端。

相关推荐
深紫色的三北六号6 小时前
Linux 服务器磁盘扩容与目录迁移:rsync + bind mount 实现服务无感迁移(无需修改配置)
linux·扩容·服务迁移
SudosuBash10 小时前
[CS:APP 3e] 关于对 第 12 章 读/写者的一点思考和题解 (作业 12.19,12.20,12.21)
linux·并发·操作系统(os)
dkbnull16 小时前
深入理解Spring两大特性:IoC和AOP
spring boot
哈基咪怎么可能是AI20 小时前
为什么我就想要「线性历史 + Signed Commits」GitHub 却把我当猴耍 🤬🎙️
linux·github
洋洋技术笔记21 小时前
Spring Boot条件注解详解
java·spring boot
十日十行2 天前
Linux和window共享文件夹
linux
木心月转码ing2 天前
WSL+Cpp开发环境配置
linux
洋洋技术笔记2 天前
Spring Boot配置管理最佳实践
spring boot
用户8307196840823 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
大道至简Edward3 天前
Spring Boot 2.7 + JDK 8 升级到 Spring Boot 3.x + JDK 17 完整指南
spring boot·后端