技術(shù)分享 | 實戰(zhàn)詳解接口測試請求方式Get矾瑰、post
本文節(jié)選自霍格沃茲測試開發(fā)學社內(nèi)部教材
在日常的工作當中瑰谜,http 請求中使用最多的就是 GET 和 POST 這兩種請求方式执解。那么掌握這兩種請求方式的原理,以及兩種請求方式的異同哲身,也是之后做接口測試一個重要基礎(chǔ)辩涝。
GET、POST的區(qū)別總結(jié)
1勘天、請求方法不同
2怔揩、post 可以附加 body,可以支持 form脯丝、json商膊、xml、binary 等各種數(shù)據(jù)格式
3宠进、從行業(yè)通用規(guī)范的角度來說晕拆,如果對數(shù)據(jù)庫不會產(chǎn)生數(shù)據(jù)變化的,比如查詢操作材蹬,建議使用 GET 請求实幕,數(shù)據(jù)的寫入與狀態(tài)建議用 POST 請求
4、
演示環(huán)境搭建
為了避免其他因素的干擾堤器,使用 flask 編寫一個簡單的 demo server昆庇。
1、安裝 flask
pip install flask
- 創(chuàng)建一個 hello.py 文件
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route("/request", methods=['POST', 'GET'])
def hellp():
#拿到request參數(shù)
query = request.args
#拿到request form
post = request.form
#分別打印拿到的參數(shù)和form
return f"query: {query}\n"\
f"post: {post}"
- 啟動服務
export FLASK_APP=hello.py
flask run
提示下面信息則表示搭建成功
* 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)
cURL命令發(fā)起GET、POST請求
發(fā)起 GET 請求,a赋朦、b 參數(shù)放入 URL 中發(fā)送,并保存在 get 文件中
curl 'http://127.0.0.1:5000/request?a=1&b=2' -v -s &>get
發(fā)起 POST 請求表蝙,a、b 參數(shù)以 form-data 格式發(fā)送乓旗,并保存在 post 文件中
curl 'http://127.0.0.1:5000/request?' -d "a=1&b=2" -v -s &>post
注意:>的右邊為請求內(nèi)容府蛇,<右邊為響應內(nèi)容
GET 請求過程
* 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([])
POST 請求過程
* 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')])
對兩個文件進行對比:
[圖片上傳失敗...(image-235922-1658284662006)]
從圖中可以清楚看到 GET 請求的 method 為 GET,POST 請求的 method 為 POST寸齐,此外欲诺,GET 請求沒有 Content-Type 以及 Content-Length 這兩個字段抄谐,而請求行中的 URL 帶有 query 參數(shù)是兩種請求都允許的格式。