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

相关推荐
A小辣椒11 小时前
TShark:Wireshark CLI 功能
linux
A小辣椒15 小时前
TShark:基础知识
linux
AlfredZhao17 小时前
OCI 明明分配了 200G 系统盘,为什么 df 只看到 30G?
linux·oci
用户3521802454751 天前
当 Prompt 学会"热更新":Spring Boot × Nacos3 AI 实战
java·spring boot·ai编程
AlfredZhao1 天前
vi 删除指定范围的行,不用再反复按 dd
linux·vi
昵称为空C1 天前
手撸一个动态 SQL 执行引擎:不重启服务,在线增删改查任意数据库
spring boot·后端
用户9718356334662 天前
银河麒麟 KY10 申威(SW64) 安装 nginx-1.16.1-2.p01.ky10.sw_64.rpm 详细步骤
linux
猪脚踏浪2 天前
linux 拷贝文件或目录到指定的位置
linux
摇滚侠2 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql