Solo  当前访客:1 开始使用


在 HTTP 请求中,Content-Type

Content-Type 是什么

在 HTTP 请求中,客户端在不同的场景下给服务器发送(有请求体的post、put请求等,get请求没有请求体,理论上没有content-type参数,如果有的话也没影响)的数据是不同的,所以格式也是不同的;约定好数据的格式,服务器端才能正确解析数据。

种类有哪些?

text/* : css script html plain 等

application/json json格式的数据,在ajax中用

application/x-www-form-urlencoded HTML中form表单的提交

multipart/form-data 文件上传的表单数据,在ajax中用

image/* 图片

audio/* 音频

font/* 字体

如何设置?

多数情况下不需要自己去手动设置,但在ajax请求中,application/jsonmultipart/form-data 需要注意,有文件上传的就选择 multipart/form-data,用FormDate对象,例子:

var formData = new FormData();

formData.append("username", "Groucho");
formData.append("accountnum", 123456); //数字 123456 会被立即转换成字符串 "123456"

// HTML 文件类型 input,由用户选择
formData.append("userfile", fileInputElement.files[0]);

// JavaScript file-like 对象
var content = '<a id="a"><b id="b">hey!</b></a>'; // 新文件的正文
var blob = new Blob([content], { type: "text/xml" });

formData.append("webmasterfile", blob);

var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);

HttpServletRequest如何获取

get请求的参数

request.getParameter("xxx");//获取单个参数

request.getParameterNames(); request.getParameterValues(name);//获取全部参数名

获取Content-Type的值

HttpServletRequest request; // HttpServletRequest 对象

String contentType = request.getContentType(); // 获取 contentType 类型

if (contentType.contains("application/json")) {} // 判断请求体的数据格式

从MultipartHttpServletRequest 获取文件

if (request instanceof MultipartHttpServletRequest) {}

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

Map<String, MultipartFile> files = multipartRequest.getFileMap();

用流获取请求体的中的json数据

用ObjectMapper的readValue方法将字符串转为实体类对象

 StringBuilder sb = new StringBuilder();  
    String line;  
    try (BufferedReader reader = request.getReader()) {  
        while ((line = reader.readLine()) != null) {  
            sb.append(line).append('\n');  
        }  
    }  
    String json = sb.toString(); // 获取请求体的完整内容(JSON字符串)  
  
    ObjectMapper objectMapper = new ObjectMapper(); // 创建ObjectMapper实例  
    MyRequestBody myRequestBody = objectMapper.readValue(json, MyRequestBody.class); // 将JSON字符串转换为Java对象  
  

同一个请求中读取请求体的次数为一次

request调用getReader() 或 getInputStream()只有一次,防止数据被多次读取

所以在spring MVC 架构中,不需要在拦截器或者过滤器中手动读取请求体中的数据了


标题:在 HTTP 请求中,Content-Type
作者:temp12138
地址:https://solo.mfyzl.icu/articles/2024/03/13/1710337616113.html

标签:
新一篇: OncePerRequestFilter 过滤器 旧一篇: 补办燃气卡的体验