在 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));