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>
相关推荐
你怎么知道我是队长32 分钟前
C语言---文件读写
java·c语言·开发语言
咕白m62540 分钟前
通过 C# 快速生成二维码 (QR code)
后端·.net
踏浪无痕1 小时前
架构师如何学习 AI:三个月掌握核心能力的务实路径
人工智能·后端·程序员
小毅&Nora1 小时前
【后端】【SpringBoot】① 源码解析:从启动到优雅关闭
spring boot·后端·优雅关闭
嘻哈baby1 小时前
从TIME_WAIT爆炸到端口耗尽:Linux短连接服务排查与优化
后端
wszy18091 小时前
外部链接跳转:从 App 打开浏览器的正确姿势
java·javascript·react native·react.js·harmonyos
开心就好20251 小时前
iOS应用性能监控全面解析:CPU、内存、FPS、卡顿与内存泄漏检测
后端
期待のcode1 小时前
认识Java虚拟机
java·开发语言·jvm
raining_peidx1 小时前
xxljob源码
java·开发语言
肥猪猪爸1 小时前
双重检查锁(DCL)与 volatile 的关键作用
java·开发语言·单例模式