application/json,application/x-www-form-urlencoded,Content-Type

  1. application/x-www-form-urlencoded
    常用的form表單提交方式, header中Content-Type 被指定為 application/x-www-form-urlencoded; 以key=value&key1=value2的形式提交。
    實際的請求形式:
    POST http://www.aaa.com HTTP/1.1
    Content-Type: application/x-www-form-urlencoded;charset=utf-8

title=test&desc=test
例如: vue axios

 axios({
        url: '/https://www.runoob.com/try/ajax/json_demo.json',
        method: 'post',
        data: {
          name: 'john',
          sex: 'M',
      desc:'一個例子'
        },
        transformRequest: function (data) {
          let params = ''
          for (let item in data) {
          
            params += encodeURIComponent(item) + '=' + encodeURIComponent(data[item]) + '&'
          }
     // alert(params)
          return params
        },
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      })

Spring中用@RequestParam來處理Content-Type為application/x-www-form-urlencoded數(shù)據(jù)。修飾的對象可以是基本數(shù)據(jù)類型和自定義對象。

  1. multipart/form-data
    表單上傳文件時content-type 使用這個。生成了一個 boundary 用于分割不同的字段,為了避免與正文內(nèi)容重復,boundary 很長很復雜。
    實際的請求形式:
    POST http://www.example.com HTTP/1.1
    Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA

------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="text"

title
------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="file"; filename="chrome.png"
Content-Type: image/png

PNG ... content of chrome.png ...
------WebKitFormBoundaryrGKCBY7qhFd3TrwA--

<html>
<head>
  <title></title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://cdn.bootcss.com/vue/2.3.4/vue.js"></script>
  <script src="https://cdn.bootcss.com/axios/0.16.2/axios.js"></script>
</head>
<body>
<form>
    <input type="text" value="" v-model="name" placeholder="請輸入用戶名">
    <input type="text" value="" v-model="age" placeholder="請輸入年齡">
    <input type="file" @change="getFile($event)">
    <button @click="submitForm($event)">提交</button>
  </form>
 </body>
  <script>
    window.onload = function () {
      Vue.prototype.$http = axios;
      new Vue({
        el: 'form',
        data: {
          name: '',
          age: '',
          file: ''
        },
        methods: {
          getFile(event) {
            this.file = event.target.files[0];
            console.log(this.file);
          },
          submitForm(event) {
            event.preventDefault();
            let formData = new FormData();
            formData.append('name', this.name);
            formData.append('age', this.age);
            formData.append('file', this.file);
 
            let config = {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            }
 
            this.$http.post('/upload', formData, config).then(function (res) {
              if (res.status === 2000) {
                /*這里做處理*/
              }
            })
          }
        }
      })
    }
  </script>
</html>

spring 可以使用@RequestPart處理接收到的文件。

/**
     * 單文件上傳
     * @param file
     * @param bucket
     * @return
     */
    @RequestMapping("uploadFile")
    public JsonResult uploadFile(@RequestPart("file") MultipartFile file, @RequestParam String bucket){

        String fileUrl = aliossService.uploadFile(file, bucket);
        Map<String,String> result = new HashMap<>();
        result.put("fileUrl",fileUrl);

        return success(result);
    }
  1. application/json
    application/json作為請求頭,用來告訴服務端消息主體是序列化的JSON字符串。
    vue 默認就是使用的content-type: aplication/json
    實際發(fā)送的請求:
    POST http://www.aaa.com HTTP/1.1
    Content-Type: application/json;charset=utf-8

{"title":"test","sub":[1,2,3]}

springMVC:
必須用@RequestBody來修飾接收到的post body內(nèi)的對象。
前端:
vue axios:
axios({
method: 'post',
url: '/saveUser',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
接受:

@RequestMapping(value = "/saveUser", method = RequestMethod.POST, consumes = "application/json; charset=utf-8")
    public ResponseEntity<String> saveUser(@RequestBody User user){} 

vue axios:
axios({
method: 'get',
url: '/user/123',
data: {
}
});
獲?。?/p>

@RequestMapping(value = "/user/{userId}", method = RequestMethod.GET, produces="application/json")  
@ResponseBody  
public User getUser(@PathVariable String UserId, Model model) {}  

4.text/xml
一種使用 HTTP 作為傳輸協(xié)議,XML 作為編碼方式的遠程調(diào)用規(guī)范。
主要是使用

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容