0%

http_content-type

HTTP Content-Type

x-www-form-urlencoded

先看一个例子:

1
2
3
4
5
6
7
8
9
<form
action="/urlencoded?firstname=philip&lastname=zhang"
enctype="application/x-www-form-urlencoded"
method="POST"
>
<input name="username" type="text" value="user1" />
<input name="password" type="text" value="pwd1" />
<input type="submit" value="Submit" />
</form>

这里的 enctype 属性指定了表单数据的编码类型,application/x-www-form-urlencoded 是默认的编码类型,也是最常用的编码类型。当表单数据被编码为 application/x-www-form-urlencoded 时:

  • 表单数据会被编码为键值对,键值对之间用 & 连接。
  • 键和值之间用 = 连接。

上面的例子中,表单数据被编码为 username=user1&password=pwd1。(实际上和url中的参数格式一样,所以才叫urlencoded

用浏览器打开这个页面,然后点击 Submit 按钮,按F12打开开发者工具,切换到 Network 选项卡,在HeadersTab可以看到请求的 Content-Typeapplication/x-www-form-urlencoded
alt text

PayloadTab可以看到请求的详细信息:

  • Query Stringfirstname=philip&lastname=zhang - 对应form action中的url参数
  • Form Datausername=user1&password=pwd1- 对应form体中的两个input

alt text

但是,上面这个例子并没有展示出url-encoded的精髓,这里的encoded到底encoded了什么呢?我们来看一个更加直观的例子:

1
2
3
4
5
6
7
8
9
<form
action="/urlencoded?firstname=philip&lastname=zhang"
enctype="application/x-www-form-urlencoded"
method="POST"
>
<input name="username" type="text" value="foo&bar" />
<input name="password" type="text" value="1=2?" />
<input type="submit" value="Submit" />
</form>

这里的 usernamepassword 的值中包含了 &=,这些字符在url中有特殊含义,如果直接放在url中,会导致url解析错误。但是,当表单数据被编码为 application/x-www-form-urlencoded 时,这些特殊字符会被转义,所以编码后的表单数据如下图所示。

  • username: foo%26bar, 其中 %26& 的转义
  • password: 1%3D2%3F, 其中 %3D= 的转义,%3F? 的转义
    如果不转义的话那么最终的结果就是username=foo&bar&password=1=2?,此时浏览器就懵逼了。导致数据解析出错。
    alt text

那么到底哪些字符需要编码呢?参考这里:http://www.blooberry.com/indexdot/html/topics/urlencoding.htm

multipart/form-data

application/json

text/plain

references