当前位置: 首页 > ops >正文

HTTP 请求中的 `Content-Type` 类型详解及前后端示例(Vue + Spring Boot)

在 HTTP 协议中,Content-Type 是一个非常关键的请求头字段,它用于指示发送给接收方的数据类型。正确设置 Content-Type 对于前后端数据交互至关重要。

本文将详细介绍常见的 Content-Type 类型,并结合 Vue 前端Spring Boot 后端 的实际开发场景,演示如何设置、传递参数以及后端如何接收这些参数。


一、什么是 Content-Type?

Content-Type 是 HTTP 请求或响应头中的一个字段,用来指定消息体(body)的媒体类型(MIME type)。它的格式如下:

Content-Type: <media-type>

例如:

Content-Type: application/json

二、常见的 Content-Type 类型

类型MIME 类型描述
application/jsonapplication/jsonJSON 格式数据,现代 Web 开发中最常用的格式
application/x-www-form-urlencodedapplication/x-www-form-urlencoded表单提交的标准格式,键值对形式
multipart/form-datamultipart/form-data上传文件时使用,支持二进制文件和文本混合
text/xmlapplication/xmltext/xml / application/xmlXML 格式数据
application/octet-streamapplication/octet-stream二进制流数据,常用于下载文件

三、不同 Content-Type 的使用场景与示例

1. application/json

使用场景:
  • 发送结构化数据(如对象、数组)
  • 前后端分离项目中常见
Vue 示例(使用 axios):
import axios from 'axios';// 第一个请求
axios.post('/api/login', {username: 'admin',password: '123456'
}, {headers: {'Content-Type': 'application/json'}
});// 第二个请求
axios.post('/api/login2', id, {headers: {'Content-Type': 'application/json'}
});
Spring Boot 接收方式:
@RestController
public class UserController {@PostMapping("/login")public ResponseEntity<?> login(@RequestBody User user) {return ResponseEntity.ok("Received: " + user.getUsername());}@PostMapping("/login2")public ResponseEntity<?> login2(@RequestBody Long id) {return ResponseEntity.ok("Received: " + id);}static class User {private String username;private String password;// getters and setters}
}

2. application/x-www-form-urlencoded

使用场景:
  • HTML 表单默认提交方式
  • 不适合复杂嵌套结构
Vue 示例(使用 qs 库序列化):
npm install qs
import axios from 'axios';
import qs from 'qs';const data = qs.stringify({username: 'admin',password: '123456'
});axios.post('/api/login', data, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
Spring Boot 接收方式:
@PostMapping("/login")
public ResponseEntity<?> login(@RequestParam String username, @RequestParam String password) {return ResponseEntity.ok("Received: " + username);
}

或者使用 Map 接收多个参数:

@PostMapping("/login")
public ResponseEntity<?> login(@RequestParam Map<String, String> params) {return ResponseEntity.ok("Received: " + params.get("username"));
}

3. multipart/form-data

使用场景:
  • 文件上传
  • 包含文件和表单数据混合的情况
Vue 示例(使用 FormData):
<template><input type="file" @change="uploadFile">
</template><script>
import axios from 'axios';export default {methods: {uploadFile(event) {const file = event.target.files[0];const formData = new FormData();formData.append('file', file);axios.post('/api/upload', formData, {headers: {'Content-Type': 'multipart/form-data'}});}}
};
</script>
Spring Boot 接收方式:
@PostMapping("/upload")
public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file) {return ResponseEntity.ok("Received file: " + file.getOriginalFilename());
}

如果同时传参和文件:

// Vue 端添加额外字段
formData.append('username', 'admin');
@PostMapping("/upload")
public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file,@RequestParam("username") String username) {return ResponseEntity.ok("User: " + username + ", File: " + file.getOriginalFilename());
}

4. application/octet-stream

使用场景:
  • 下载文件或传输原始二进制数据
Vue 示例(Blob 数据):
axios.get('/api/download', {responseType: 'blob'
}).then(response => {const url = window.URL.createObjectURL(new Blob([response.data]));const link = document.createElement('a');link.href = url;link.setAttribute('download', 'file.txt');document.body.appendChild(link);link.click();
});
Spring Boot 返回方式:
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() throws IOException {Path path = Paths.get("path/to/file.txt");Resource resource = new UrlResource(path.toUri());return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"").body(resource);
}

四、总结对比表

Content-Type用途Vue 传参方式Spring Boot 接收方式
application/json结构化数据直接传对象@RequestBody
application/x-www-form-urlencoded表单数据qs.stringify()@RequestParam, Map
multipart/form-data文件上传FormDataMultipartFile
application/octet-stream二进制数据responseType: 'blob'返回 Resource

五、注意事项

  • JSON 格式必须严格符合语法规范,否则后端无法解析。
  • 上传文件时不能使用 JSON,必须使用 multipart/form-data
  • 使用 FormData 时不要手动设置 Content-Type ,浏览器会自动处理边界(boundary)。
  • 如果使用了全局拦截器或封装了 axios 实例,请确保 headers 设置生效。

六、扩展:其他 Content-Type 类型

类型说明
text/plain纯文本
text/htmlHTML 文档
application/pdfPDF 文件
image/jpeg, image/png图片格式
video/mp4, audio/mpeg音视频格式

七、结语

掌握 Content-Type 是前后端交互的基础,尤其在 Vue + Spring Boot 架构下,合理选择和设置 Content-Type 可以显著提升接口的健壮性和易用性。希望本篇文章能帮助你更清晰地理解不同类型的使用场景和实现方式。

如果你觉得这篇文章对你有帮助,欢迎点赞、收藏或转发!

📌 相关阅读推荐:

  • Vue + Spring Boot 前后端交互实践:正确使用 Content-Type: application/json 及参数传递方式

如有疑问或建议,欢迎留言交流!

http://www.xdnf.cn/news/14464.html

相关文章:

  • 腾讯云国际站缩容:策略、考量与实践
  • Vue-7-前端框架Vue之应用基础从Vue2语法到Vue3语法的演变
  • C/C++中的位段(Bit-field)是什么?
  • 单片机 - STM32读取GPIO某一位时为什么不能直接与1判断为高电平?
  • 【开源工具】Windows屏幕控制大师:息屏+亮度调节+快捷键一体化解决方案
  • Day03_数据结构(顺序结构单向链表单向循环链表双向链表双向循环链表)
  • 【一天一个知识点】RAG(Retrieval-Augmented Generation,检索增强生成)构建的第一步
  • ARIMA 模型
  • Linux运维新人自用笔记(部署 ​​LAMP:Linux + Apache + MySQL + PHP、部署discuz论坛)
  • 内存泄漏到底是个什么东西?如何避免内存泄漏
  • 楞伽经怎么读
  • 23种设计模式图解
  • ragflow中的pyicu安装与测试
  • 基于YOLOv8+Deepface的人脸检测与识别系统
  • WSL备份与还原
  • 车载网关框架 --- CAN/CANFD网段路由到Ethernet网段时间
  • sparseDrive(2):环境搭建及效果演示
  • C++11函数封装器 std::function
  • 卫星通信链路预算之一:信噪比分配
  • JavaSE: 数组详解
  • JSONP 跨域请求原理解析与实践
  • RabbitMQ消息队列实战指南
  • 亚马逊选品时怎么选择一个产品
  • 智能土木通 - 土木工程专业知识问答系统01:项目简介
  • 逆元 Inverse element
  • c语言学习_函数4
  • 【Dify系列】【Dify 核心功能】【应用类型】【四】【Chatflow】
  • Science 正刊:脊髓损伤患者的复杂触觉离现实又近了一步
  • 观察者模式Observer Pattern
  • 基于STM32的超声波模拟雷达设计