POST四种请求格式 前后端代码示例

application/json

服务器端使用spring boot

@RestController
public class GreetingController {

    //解析application/json
    @RequestMapping(value = "/hello", method = RequestMethod.POST)
    public Object getJson(@RequestBody Object obj) {
        return obj;
    }

}
复制代码

客户端,原生ajax

    var xhr = new XMLHttpRequest()

    xhr.onreadystatechange = function (ev) {
        console.log(xhr.readyState);
        if (xhr.readyState === 4){
            if (xhr.status === 200){
                console.log(xhr.responseText);
            } else {
                console.error(xhr.statusText);
            }
        }
    };

    xhr.open('POST','/hello');
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify({ name:'zhuwei', age:'25', hobby:'ball'}))
复制代码

浏览器请求详情

application/x-www-form-urlencoded

服务端,springboot

@RestController
public class GreetingController {

    //解析application/x-www-form-urlencoded
    @RequestMapping(value = "/helloFormUrl", method = RequestMethod.POST)
    public String getForm(@RequestParam("name") String name,@RequestParam("age") String age) {
        return "name="+name+"&"+"age="+age;
    }
}
复制代码

客户端,html form 表单

<form action="/helloFormUrl" method="post">
    <input type="text" name="name">
    <input type="text" name="age">
    <input type="submit">
</form>
复制代码

或者使用 ajax

    var xhr = new XMLHttpRequest()

    xhr.onreadystatechange = function (ev) {
        console.log(xhr.readyState);
        if (xhr.readyState === 4){
            if (xhr.status === 200){
                console.log(xhr.responseText);
            } else {
                console.error(xhr.statusText);
            }
        }
    };
    
	//生成 post 参数 params,有三种方法,选一种
    //1. 使用URLSearchParams 接口,会对内容进行utf8编码
    const params = new URLSearchParams();
    params.append('name', '小明');
    params.append('age', '18');
    
    //2.使用encodeURIComponent 对内容进行编码
    //好处是url中的汉字等一些特殊字符会被转为utf8编码,减少出错
	const params = "name="+encodeURIComponent("小明")+"&age="+encodeURIComponent("19")  
	
	//3.不编码直接写,可能服务端会解码错误
    const params = "name=小明&age=19"
   
    xhr.open('POST','http://localhost:1234/helloFormUrl');
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send(params)
复制代码

浏览器请求详情

multipart/form-data

1.发送键值对

服务端,springboot(和 application/x-www-form-urlencoded 的代码相同)


    @RequestMapping(value = "/helloFormUrl", method = RequestMethod.POST)
    public String getForm(@RequestParam("name") String name,@RequestParam("age") String age) {
        return "name="+name+"&"+"age="+age;
    }
复制代码

客户端,ajax。

注意:

  1. 使用FormData()生成数据
  2. 不手动添加content-type请求头
    var xhr = new XMLHttpRequest()

    xhr.onreadystatechange = function (ev) {
        console.log(xhr.readyState);
        if (xhr.readyState === 4){
            if (xhr.status === 200){
                console.log(xhr.responseText);
            } else {
                console.error(xhr.statusText);
            }
        }
    };

   
    const params = new FormData();
    params.append('name', '朱维');
    params.append('age', '18');

    xhr.open('POST','http://localhost:1234/helloFormUrl');
   
    xhr.send(params)
复制代码

2.发送文件

服务端代码

@CrossOrigin
@RestController
public class GreetingController {

    @RequestMapping(value = "/helloFile", method = RequestMethod.POST)
    public void getFile(@RequestParam("file") MultipartFile file) {
        System.out.print(file.getSize());
    }

}
复制代码

客户端采用<input type=file>发送文件

注意:form需要加上enctype="multipart/form-data",因为form表单的默认编码方式是application/x-www-form-urlencoded

<form action="http://localhost:1234/helloFile" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
</form>
复制代码

text/plain

服务端

    @RequestMapping(value = "/helloText", method = RequestMethod.POST)
    public void getText(@RequestBody String str) {
        System.out.print(str);
    }
复制代码

客户端

    var xhr = new XMLHttpRequest()

    xhr.onreadystatechange = function (ev) {
        console.log(xhr.readyState);
        if (xhr.readyState === 4){
            if (xhr.status === 200){
                console.log(xhr.responseText);
            } else {
                console.error(xhr.statusText);
            }
        }
    };

    xhr.open('POST','http://localhost:1234/helloText');
    xhr.setRequestHeader('Content-Type', 'text/plain');
    xhr.send('我是小明')
复制代码

总结

  1. POST常用发送方式有四种,其实是http请求的四种content-type
    • application/json
    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain
  2. 表单提交默认使用 application/x-www-form-urlencoded,可以通过设置enctype属性改变默认提交方式,表单不支持application/json类型。想发json类型的请求,只能通过ajax。
  3. 上传文件只能通过multipart/form-data,但multipart/form-data也可以传键值对
PS:本文并没有涉及太多的细节讲解,因为本人也是刚开始学习POST请求,所以总结了一些学习过程中做的demo代码,如果有写得不恰当的地方,还请指正。

参考文献

关于URL编码-阮一峰
Spring web annotations
阮一峰js标准参考教程-ajax

转载于:https://juejin.im/post/5bac48aa6fb9a05d147829c4

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值