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 小时前
kali-linux 虚拟机连接安卓模拟器
android·linux·运维·虚拟机连接模拟器·安卓模拟器,linux虚拟机
吳所畏惧1 小时前
Linux环境/麒麟V10SP3下离线安装Redis、修改默认密码并设置Redis开机自启动
linux·运维·服务器·redis·中间件·架构·ssh
yueguangni2 小时前
sysstat 版本 10.1.5 是 CentOS 7 的默认版本,默认情况下确实不显示 %wait 字段。需要升级到新版sysstat
linux·运维·centos
+VX:Fegn08952 小时前
计算机毕业设计|基于springboot + vue在线音乐播放系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
+VX:Fegn08953 小时前
计算机毕业设计|基于springboot + vue律师咨询系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
萧曵 丶3 小时前
Linux 业务场景常用命令详解
linux·运维·服务器
Arwen3033 小时前
SSL 加密证书助力企业构建安全的网络环境
网络·网络协议·tcp/ip·安全·php·ssl
豆是浪个4 小时前
Linux(Centos 7.6)命令详解:ps
linux·windows·centos
困知勉行19854 小时前
springboot整合redis
java·spring boot·redis
Run_Teenage4 小时前
Linux:深刻理解缓冲区
linux