Http POST请求数据提交格式

做开发时,会用到post提交数据,原来是用httpmime包来处理数据封装, 但为了一个小需求,引入一个几十kb的jar,总感觉不值,学习一下post请求的格式,自己顺便练下手,实现一个

服务端通常是根据请求头(headers)中的 Content-Type 字段来获知请求中的消息主体是用何种方式编码,再对主体进行解析。所以说到 POST 提交数据方案,包含了 Content-Type 和消息主体编码方式两部分。

application/x-www-form-urlencoded

最基本的form表单结构,用于传递字符参数的键值对,请求结构如下

POST  HTTP/1.1
Host: www.demo.com
Cache-Control: no-cache
Postman-Token: 81d7b315-d4be-8ee8-1237-04f3976de032
Content-Type: application/x-www-form-urlencoded

key=value&testKey=testValue

请求头中的Content-Type设置为application/x-www-form-urlencoded; 提交的的数据,请求body中按照 key1=value1&key2=value2 进行编码,key和value都要进行urlEncode;

multipart/form-data

这是上传文件时,最常见的数据提交方式,看一下请求结构

POST  HTTP/1.1
Host: www.demo.com
Cache-Control: no-cache
Postman-Token: 679d816d-8757-14fd-57f2-fbc2518dddd9
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="key"

value
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="testKey"

testValue
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="imgFile"; filename="no-file"
Content-Type: application/octet-stream


<data in here>
------WebKitFormBoundary7MA4YWxkTrZu0gW--

首先请求头中的Content-Type 是multipart/form-data; 并且会随机生成一个boundary, 用于区分请求body中的各个数据; 每个数据以 --boundary 开始, 紧接着换行,下面是内容描述信息, 接着换2行, 接着是数据; 然后以 --boundary-- 结尾, 最后换行;

文本数据和文件,图片的内容描述是不相同的
文本参数:

Content-Disposition: form-data; name="key"
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

文件参数:

Content-Disposition: form-data; name="imgFile"; filename="no-file"
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary

每个换行都是 \r\n ;

application/json

text/xml

text/plain

请求头的Content-Type设置为这几个也很常见, 不过一般是在web前端开发中,请求body没有固定结构, 直接传输对应数据的数据流, 不必和上面2种样, 还要用固定的结构包起来, 只不过数据对应的是json, xml, 文本;



作者:Simon_z
链接:https://www.jianshu.com/p/4f9e79eb0163
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

猜你喜欢

转载自blog.csdn.net/u010020099/article/details/83866984