x-www-form-urlencoded和multipart/form-data的区别

结论

当有二进制数据传输时,使用 multipart/form-data,否则使用 x-www-form-urlencoded。

区别

x-www-form-urlencoded 和 multipart/form-data 是HTTP协议中,向服务器发送POST请求时的两种编码方案,对应form表单的enctype属性。

<!DOCTYPE html>
<html>
<head> 
    <meta charset="utf-8"> 
</head>
<body>
    <form action="/" method="POST" enctype="application/x-www-form-urlencoded">
        姓名: <input type="text" name="name"><br>
        年龄: <input type="text" name="age">
        <input type="submit" value="提交">
    </form>
</body>
</html>

x-www-form-urlencoded

默认情况下,使用该编码,数据通过 name/value 数据对传输。

POST / HTTP/1.1
Host: localhost:8080
Content-Length: 233

name=june&age=12

如果编码中含有unicode字符,则需要进行转换处理后再传输,比如:

name=%E6%B5%8B%E8%AF%95&age=12

以%开头后跟两个十六进制,代表一个字节,使用utf-8编码将字符转为字节序列。

multipart/form-data

当需要上传文件时,使用该编码。数据以指定的分隔符分开,数据也无需编码转换。

POST / HTTP/1.1
Host: localhost:8080
Content-Length: 233
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryfPIuyKYREDzq8zXG

------WebKitFormBoundaryfPIuyKYREDzq8zXG
Content-Disposition: form-data; name="name"

张三
------WebKitFormBoundaryfPIuyKYREDzq8zXG
Content-Disposition: form-data; name="age"

12
------WebKitFormBoundaryfPIuyKYREDzq8zXG--

现在流行restful风格的接口,请求体使用json作为数据格式,对应的Content-Type为 application/json

参考资料

application-x-www-form-urlencoded-or-multipart-form-data

原文地址:https://www.cnblogs.com/junejs/p/12686884.html