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

相关推荐
唐青枫1 小时前
别再只会用 cron:Linux systemd Timer 定时任务实战详解
linux
Flittly1 天前
【AgentScope Java新手村系列】(14)人机交互
java·spring boot·spring
Flynt2 天前
从Spring Boot 4.0升到4.1,我在Maven和gRPC上栽了跟头
java·spring boot·后端
AlfredZhao2 天前
生产环境里,为什么不建议把普通端口直接暴露到公网?
linux·https·443·80
MrSYJ2 天前
TCP协议理解
后端·tcp/ip
掉鱼的猫3 天前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
java·spring boot
戴为沐3 天前
Linux内存扩容指南
linux
zylyehuo3 天前
Linux 彻底且安全地删除文件
linux
人活一口气4 天前
Spring Boot与AIGC的完美结合:从零搭建智能内容生成平台
java·spring boot·aigc
用户805533698034 天前
主线 U-Boot 上 RK3506:和闭源 rkbin 拔河的三个隐性契约
linux·嵌入式