方式一:application/json

  1. @RestController
  2. public class GreetingController {
  3. //解析application/json
  4. @RequestMapping(value = "/hello", method = RequestMethod.POST)
  5. public Object getJson(@RequestBody Object obj) {
  6. return obj;
  7. }
  8. }

客户端,原生ajax

  1. var xhr = new XMLHttpRequest()
  2. xhr.onreadystatechange = function (ev) {
  3. console.log(xhr.readyState);
  4. if (xhr.readyState === 4){
  5. if (xhr.status === 200){
  6. console.log(xhr.responseText);
  7. }
  8. }
  9. };
  10. xhr.open('POST','/hello');
  11. xhr.setRequestHeader('Content-Type', 'application/json');
  12. xhr.send(JSON.stringify({ name:'zhuwei', age:'25', hobby:'ball'}))

客户端,axios

  1. export function hello(data) {
  2. return request({
  3. url: '/hello',
  4. method: 'post',
  5. data: JSON.stringify(data),
  6. headers: {
  7. 'Content-Type': 'application/json;charset=UTF-8'
  8. }
  9. })
  10. }

方式二:application/x-www-form-urlencoded

  1. @RestController
  2. public class GreetingController {
  3. //解析application/x-www-form-urlencoded
  4. @RequestMapping(value = "/helloFormUrl", method = RequestMethod.POST)
  5. public String getForm(@RequestParam("name") String name,
  6. @RequestParam("age") String age) {
  7. return "name="+name+"&"+"age="+age;
  8. }
  9. }

客户端,html form 表单

  1. <form action="/helloFormUrl" method="post">
  2. <input type="text" name="name" />
  3. <input type="text" name="age" />
  4. <input type="submit" />
  5. </form>

或者使用 ajax

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

客户端 axios

  1. // 方式一
  2. const formData = new FormData();
  3. formData.append('name', '小明')
  4. formData.append('age', '18')
  5. // 方式三
  6. const params = new URLSearchParams();
  7. params.append('name', '小明');
  8. params.append('age', '18');
  9. export function hello(data) {
  10. return request({
  11. url: '/helloFormUrl',
  12. method: 'post',
  13. data: data,
  14. headers: {
  15. 'Content-Type': 'application/x-www-form-urlencoded'
  16. }
  17. })
  18. }
  1. import qs from 'qs'
  2. export function hello(data) {
  3. return request({
  4. url: '/helloFormUrl',
  5. method: 'post',
  6. data: qs.stringify(data),
  7. headers: {
  8. 'Content-Type': 'application/x-www-form-urlencoded'
  9. }
  10. })
  11. }

使用qs序列化时,后台接收参数有变化

  1. @RestController
  2. public class GreetingController {
  3. //解析application/x-www-form-urlencoded
  4. @RequestMapping(value = "/helloFormUrl", method = RequestMethod.POST)
  5. public String getForm(User user) {
  6. return "name="+name+"&"+"age="+age;
  7. }
  8. }
  9. class User {
  10. private String name;
  11. private String age;
  12. // get/set
  13. }

方式三: multipart/form-data

1.发送键值对

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

  1. @RequestMapping(value = "/helloFormUrl", method = RequestMethod.POST)
  2. public String getForm(@RequestParam("name") String name,
  3. @RequestParam("age") String age) {
  4. return "name="+name+"&"+"age="+age;
  5. }

客户端,ajax。
注意:

  1. 使用FormData()生成数据
  2. 不手动添加content-type请求头 ```javascript 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)

  1. <a name="sBoMx"></a>
  2. #### 2.发送文件
  3. 服务端代码
  4. ```java
  5. @CrossOrigin@RestController
  6. public class GreetingController {
  7. @RequestMapping(value = "/helloFile", method = RequestMethod.POST)
  8. public void getFile(@RequestParam("file") MultipartFile file) {
  9. System.out.print(file.getSize());
  10. }
  11. }

客户端采用发送文件
注意: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('我是小明')