Java:处理 HTTP 请求的 Content-Type

在 Java 中处理 HTTP 请求的 Content-Type,主要涉及"获取‌"、‌"判断‌ "和 ‌"响应设置‌ "三个操作。以下是关键要点:

‌1. 获取请求的 Content-Type‌

在 Servlet 或 Spring MVC 控制器中,通过 HttpServletRequest 对象获取:

String contentType = request.getContentType();

System.out.println("Content-Type: " + contentType);

该方法返回请求头中的 Content-Type 值,如 application/json、application/x-www-form-urlencoded 等 ‌。

‌2. 常见 Content-Type 类型及用途‌

‌application/json‌:发送 JSON 格式数据,常用于 REST API 。

‌application/x-www-form-urlencoded‌:表单默认提交方式,键值对形式(如 name=John&age=30)‌。

‌multipart/form-data‌:用于文件上传或混合表单数据 ‌。

‌text/plain‌:纯文本数据(较少用)‌。

‌3.根据 Content-Type 处理不同请求体‌

可在 Servlet 中根据类型分支处理:

if ("application/json".equals(contentType)) {

parseJsonRequest(request); // 解析 JSON

} else if ("application/x-www-form-urlencoded".equals(contentType)) {

parseFormRequest(request); // 解析表单参数

} else {

response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported Content-Type");

}

‌JSON 解析‌:使用 request.getReader().lines().collect(Collectors.joining()) 读取请求体 ‌。

‌表单解析‌:通过 request.getParameter("key") 获取参数 ‌。

‌4. 设置响应的 Content-Type(注意:不能修改请求的 Content-Type)‌

虽然‌无法修改客户端请求的 Content-Type‌,但可在响应中设置:

response.setContentType("application/json"); // 设置响应格式为 JSON

response.getWriter().write("{\"message\": \"success\"}");

这是标准做法,用于告知客户端如何解析响应数据 ‌。

‌5. Spring Boot 中的注解映射‌

‌@RequestParam‌:用于 application/x-www-form-urlencoded 类型请求 ‌。

‌@RequestBody‌:用于 application/json 或其他非表单类型,需配合 HttpMessageConverter ‌1。

⚠️ 注意:GET 请求无请求体,设置 Content-Type 无意义 ‌。

如需调用第三方接口并设置 Content-Type,可使用 HttpClient 或 OkHttp,例如:

HttpPost post = new HttpPost("https://api.example.com");

post.setHeader("Content-Type", "application/json");

post.setEntity(new StringEntity(jsonString));

相关推荐
丰锋ff1 天前
3.1 Qt事件之事件处理器
开发语言·qt
多弗朗皮卡丘1 天前
C语言梦开始的地方7:函数
c语言·开发语言
mldong1 天前
"applicant" 契约:退回发起人的闭环设计
java·架构
月华路1 天前
G1 垃圾回收:脏卡队列、记忆集与并发精化线程机制
java·开发语言
gugucoding1 天前
47. 【Java】Java内存模型(JMM)与可见性
java·开发语言
m0_380743871 天前
从零调用 Claude 教程
开发语言·python·node.js
起床学FPGA1 天前
AI回答问题之后,会自动跳到最下面的问题
开发语言·javascript·ecmascript
zww89491111 天前
校园跑腿系统开发实战指南:从需求分析到上线部署全流程解析
java
Fluxart.ai1 天前
电商商品图审核怎么自动化?规则引擎、人工复核与发布门禁
java·前端·自动化
x_x-F1 天前
网络数据从网卡到用户态:一场基于内存所有权转移的接力赛
开发语言·网络·php