json 请求
curl -d
可以发送header Content-Type 为 application/json 的 JSON 格式数据请求,request body就是一个json,可以直接做json反序列化完成解析
# golang
func RecvData(req *http.Request) {
bodyBytes, _ := ioutil.ReadAll(req.Body)
data := struct {
ID int `json:"id"`
}{}
json.Unmarshal(bodyBytes, &data)
}
# python
def recv_data(request):
if request.method == 'POST':
# 直接load body反序列化
received_json_data = json.loads(request.body)
return received_json_data
表单请求
form是表单,在html中以form tag进行标记,有get和post两种提交方式
<form action="http://localhost:8080/repositories" method="get">
<input type="text" name="language" value="go" />
<input type="text" name="since" value="monthly" />
<input type="submit" />
</form>
Form的method属性为get,该HTTP请求会将表单的输入文本作为查询字符串参数(Query String Parameter),在这里即是?language=go&since=monthly
放到action url的后面,得到http://localhost:8080/repositories?language=go&since=monthly
get方法提交form局限性较大,容易受到长度限制,只能传递简单的参数
<form action="http://localhost:8080/repositories" method="post">
<input type="text" name="language" value="go" />
<input type="text" name="since" value="monthly" />
<input type="submit" />
</form>
Form的method属性为post,该HTTP请求会将表单的输入文本放到body
我们知道,HTTP POST 方法 发送数据给服务器. 请求主体的类型由 Content-Type 首部指定
在这种情况下, Content-Type 是通过在 <form> 元素中设置正确的 enctype 属性, 或是在 <input> 和 <button> 元素中设置 formenctype 属性来选择的:
- application/x-www-form-urlencoded: 数据被编码成以 '&' 分隔的键-值对, 同时以 '=' 分隔键和值. 非字母或数字的字符会被 percent-encoding: 这也就是为什么这种类型不支持二进制数据(应使用 multipart/form-data 代替).
- multipart/form-data(当上传文件时,Content-Type就需要设置为此项)
- text/plain
使用默认的 application/x-www-form-urlencoded 做为 content type 的简单表单request示例:
POST / HTTP/1.1
Host: foo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13
say=Hi&to=Mom // 这里开始是body
使用 multipart/form-data 作为 content type 的表单request示例:
POST /test.html HTTP/1.1
Host: example.org
Content-Type: multipart/form-data;boundary="boundary"
--boundary // 这里开始是body
Content-Disposition: form-data; name="field1"
value1
--boundary
Content-Disposition: form-data; name="field2"; filename="example.txt"
value2
使用默认的 text/plain 做为 content type 的简单表单request示例:
POST / HTTP/1.1
Host: foo.com
Content-Type: text/plain
Content-Length: 13
say=Hi // 这里开始是body
to=Mom
可以看到,使用form传递参数,body已不再是纯粹的json,需要另作解析
这时golang使用func (r *Request) ParseMultipartForm(maxMemory int64) error
https://pkg.go.dev/net/http#Request.ParseMultipartForm