Content-Type是什么

目录

Content-Type是什么

获取方式

设置方式

常见类型

application/x-www-form-urlencoded

multipart/form-data

application/json

text/xml

text/html

text/plain


Content-Type是什么

Content-Type出现在请求标头和响应标头中,意思是内容类型,用于指定请求数据和响应数据的类型。客户端和服务端对不同数据类型的处理方式不同。

获取方式

可以通过HttpServletRequest对象来获取

java 复制代码
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class DemoController {
    
    private final HttpServletRequest request;
    
    @RequestMapping("/test")
    public String demo() {
        String contentType = request.getContentType();
        System.out.println(contentType);
        return contentType;
    }
}

测试结果:

设置方式

可以通过HttpServletResponse对象来设置

java 复制代码
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequiredArgsConstructor
public class DemoController {

    private final HttpServletResponse response;

    @RequestMapping("/test")
    public void demo() throws IOException {
        System.out.println("test success!");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/x-www-form-urlencoded;charset=utf-8");
        String value = new ObjectMapper().writeValueAsString("test success!");
        response.getWriter().write(value);
    }
}

测试结果:

常见类型

application/x-www-form-urlencoded

用于表单提交,请求方式为POST,数据以键值对的形式携带在请求体中。如果包含中文或者特殊字符,会进行URL转码。

URL转码:URL转码是将URL中的非法字符替换为特殊字符序列的过程。URL中只允许出现英文字母、数字以及部分特殊字符,而其他字符(例如中文和一些特殊字符)是不允许直接出现的。如果URL中包含了这些非法字符,就需要进行转码,将其转换为URL允许的形式。中文一般使用utf-8编码进行转码。

例如:

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form method="POST" action="http://localhost:8080/test" enctype="application/x-www-form-urlencoded">
        用户名:<input type="text" name="username" />
        密码:<input type="password" name="password" />
        <input type="submit" value="登录" />
    </form>
</body>

</html>

接收方式:

java 复制代码
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    @PostMapping("/test")
    public String demo(String username, String password) {
        return "username=" + username + "password=" + password;
    }
}

multipart/form-data

用于表单提交,请求方式为POST,上传文件。

例如:

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form method="POST" action="http://localhost:8080/test" enctype="multipart/form-data">
        上传文件:<input type="file" name="file" />
        <input type="submit" value="提交" />
    </form>
</body>

</html>

接收方式:

java 复制代码
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class DemoController {

    @PostMapping("/test")
    public String demo(MultipartFile file) {
        return file.getOriginalFilename();
    }
}

application/json

指定数据的格式为json格式。

例如:

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="js/axios.js"></script>
</head>

<body>
    <input type="button" value="获取数据POST" onclick="post()">
</body>

<script>
    function post() {
        axios({
            method: "post",
            url: "http://localhost:8080/test",
            data: {
                "username": "艾伦",
                "password": "123abc"
            }
        }).then(result => {
            console.log(result.data)
        })
    }
</script>

</html>

接收方式:

java 复制代码
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@Data
@NoArgsConstructor
public class UserLogin {
    private String username;
    private String password;
}
java 复制代码
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    @PostMapping("/test")
    public String demo(@RequestBody UserLogin userLogin) {
        return JSONObject.toJSONString(userLogin);
    }
}

text/xml

xml格式的数据,现在已经不用了,被json格式的数据代替。

text/html

html格式的数据

text/plain

Content-Type默认的值就是text/plain,纯文本,不做任何数据处理。

例如:

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form method="POST" action="http://localhost:8080/test" enctype="text/plain">
        用户名:<input type="text" name="username" />
        密码:<input type="password" name="password" />
        <input type="submit" value="登录" />
    </form>
</body>

</html>
相关推荐
元界metalite7 分钟前
SpringBoot整合RocketMQ-毒丸消息还要无限重试吗
后端
用户31268748772018 分钟前
ConcurrentHashMap 怎么保证线程安全?从分段锁到 CAS+synchronized
java
vipxieliang29 分钟前
ValidX vs Apache Commons Validator:功能与性能对比
java·spring boot
SimonKing30 分钟前
升级Spring Boot 4后,从 Jackson 2 到 3,到底有哪些变化
java·后端·程序员
YIAN34 分钟前
Docker + Nginx 核心原理扫盲:从环境隔离到反向代理,运维面试必考点
后端·docker·面试
万物智能35 分钟前
启动链路与分区—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
后端·架构
寒蝉12838 分钟前
一个简单操作是怎么在分布式环境下变复杂的
后端
苏三的开发日记39 分钟前
Windows宿主机+VMware CentOS虚拟机 + 同一个Wi-Fi下的其他实体电脑,三者可以互相访问
后端
boooooooom41 分钟前
手把手做一个图 RAG 烹饪问答系统:Neo4j + Milvus + LLM 的工程实践
前端·javascript·后端
newerp42 分钟前
Golang 切片底层结构
后端·程序员·go