在日常的工作當中,HTTP 請求中使用最多的就是 GET 和 POST 這兩種請求方式。深度掌握這兩種請求方式的原理以及異同之處,也是之後做接口測試一個重要基礎。
GET、POST 的區別總結
- 請求行的 method 不同;
- POST 可以附加 body,可以支持 form、json、xml、binary等各種數據格式;
- 從行業通用規範的角度來說,無狀態變化的建議使用 GET 請求,數據的寫入與狀態建議用 POST 請求;
演示環境搭建
為了避免其他因素的干擾,使用 Flask 編寫一個簡單的 Demo Server。
- 安裝flask
<code>pip
install flask/<code>
- 創建一個 hello.py 文件
hello.py
<code>from
flaskimport
Flask, request app = Flask (_name__)def
hello_world
()
:return
'Hello, World!'
def
hellp
()
: query = request.args post = request.formreturn
f"query:
{query}
\n"\f"post:
{post}
"/<code>
- 啟動服務
<code>export
FLASK_APP=hello.py flask run/<code>
提示下面信息則表示搭建成功。
<code>*
Serving Flask app "hello.py"*
Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead.*
Debug mode: off*
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)/<code>
CURL 命令發起 GET/POST 請求
發起 GET 請求,a、b參數放入 URL 中發送,並保存在 get 文件中:
<code>curl'http
:/<code>
發起 POST 請求,a、b參數以 form-data格式發送,並保存在post 文件中:
<code>curl
'http://127.0.0.1:5000/request?'
-d"a=1&b=2"
-V -S &>post/<code>
GET/POST 請求對比
注意:>的右邊為請求內容,
GET 請求過程
<code>*
Trying
127.0
.0
.1
...
*
TCP_NODELAY
set
*
Connected
to
127.0
.0
.1
(127.0.0.1)
port
5000
(#0)
>
GET
/request?a=1&b=2
HTTP/1.1
>
Host:
127.0
.0
.1
:5000
>
User-Agent:
curl/7.64.1
>
Accept:
*/*
>
*
HTTP
1.0
,
assume
close
after
body
<
HTTP/1.0
200
OK
<
Content-Type:
text/html;
charset=utf-8
<
Content-Length:
80
<
Server:
Werkzeug/0.14.1
Python/3.7.5
<
Date:
Wed,
01
Apr
2020
07
:35:42
GMT
<
{
[80
bytes
data]
*
Closing
connection
0
query:
ImmutableMultiDict([('a',
'1'
),
('b',
'2'
)])
post:
ImmutableMultiDict([])
/<code>
POST 請求過程
<code>*
Trying
127.0
.0
.1
...
*
TCP_NODELAY
set
*
Connected
to
127.0
.0
.1
(127.0.0.1)
port
5000
(#0)
>
POST
/request?a=1&b=2
HTTP/1.1
>
Host:
127.0
.0
.1
:5000
>
User-Agent:
curl/7.64.1
>
Accept:
*/*
>
Content-Length:
7
>
Content-Type:
application/x-www-form-urlencoded
>
}
[7
bytes
data]
*
upload
completely
sent
off:
7
out
of
7
bytes
*
HTTP
1.0
,
assume
close
after
body
<
HTTP/1.0
200
OK
<
Content-Type:
text/html;
charset=utf-8
<
Content-Length:
102
<
Server:
Werkzeug/0.14.1
Python/3.7.5
<
Date:
Wed,
01
Apr
2020
08
:15:08
GMT
<
{
[102
bytes
data]
*
Closing
connection
0
query:
ImmutableMultiDict([('a',
'1'
),
('b',
'2'
)])
post:
ImmutableMultiDict([('c',
'3'
),
('d',
'4'
)])
/<code>
對兩個文件進行對比:
從圖中可以清楚看到 GET 請求的 method 為 GET,POST 請求的 method 為 POST,此外,GET 請求沒有 Content-Type 以及 Content-Length 這兩個字段,而請求行中的 URL 帶有 query 參數,是兩種請求都允許的格式。(End)
(文章來源於霍格沃茲測試學院)
專欄
7小時入門軟件測試
0.99幣
5人已購