發(fā)送get請求
import requests
# request發(fā)送http請求
def test_no_params():
# 使用requests.get發(fā)送一個get請求。
# r = requests.get("https://www.baidu.com/")
# 使用requests.request發(fā)送一個get請求。
# r = requests.request(method="GET",url="https://www.baidu.com/")
sess = requests.session() # 使用session建立連接
r = sess.request(method="GET",url="https://www.baidu.com/") # 再發(fā)送請求,無論請求多少次,連接只建立
r = sess.request(method="GET", url="https://www.baidu.com/")
print(r.text)#text獲取響應(yīng)對象中,響應(yīng)正文的數(shù)據(jù)
def test_get_query():
# get請求帶參數(shù)
pa = {"accountName":"xuepl123"} # 把get參數(shù)都放入一個字典中
r = requests.request("GET","http://qa.yansl.com:8084/acc/getAccInfo",params=pa) # 請求時以params關(guān)鍵字傳參
print(r.text)
def test_get_path():
# get請求參數(shù)在path中
# 使用.format進行字符串格式化
r = requests.request("GET","http://qa.yansl.com:8084/acc/getAllAccs/{pageNum}/{pageSize}".format(pageNum=1,pageSize=10))
print(r.text)
def test_get_file(pub_data):
# get請求下載文件
p = {"pridCode":"63803y"}
h={"token":pub_data["token"]}
r = requests.request("GET","http://qa.yansl.com:8084/product/downProdRepertory",params=p,headers=h)
# r.content獲取響應(yīng)正文的字節(jié)碼(二進制)
with open("aa.xls","wb") as f: # with語法 打開文件,并賦值給變量f
f.write(r.content) # 把響應(yīng)中的數(shù)據(jù)寫入到文件中
發(fā)送post請求
import requests
def test_post_json_1(pub_data):
data = {
"pwd": "abc123",
"userName": "tuu653"
}
h = {"token": pub_data["token"]}
r = requests.post("http://qa.yansl.com:8084/login",json=data,headers=h) # json關(guān)鍵字發(fā)送json類型數(shù)據(jù)
print(r.text)
def test_post_json_2(pub_data):
data = '''{
"pwd": "abc123",
"userName": "tuu653"
}'''
h = {"token": pub_data["token"],"content-type":"application/json"}
r = requests.post("http://qa.yansl.com:8084/login",data=data,headers=h) # data關(guān)鍵字發(fā)送json類型數(shù)據(jù),請求頭中必須指定content-type
print(r.text)
def test_post_formdata(pub_data):
# post請求鍵值對數(shù)據(jù)
data = {
"userName": "tan242743"
}
h = {"token": pub_data["token"]}
r = requests.post("http://qa.yansl.com:8084/user/lock",data=data,headers=h) # data關(guān)鍵字發(fā)送鍵值對類型數(shù)據(jù)
print(r.text)
def test_post_upload_file(pub_data):
# post請求上傳文件
data = {
"file": open("aa.xls","rb")
}
h = {"token": pub_data["token"]}
r = requests.post("http://qa.yansl.com:8084/product/uploaProdRepertory", files=data, headers=h) # files關(guān)鍵字發(fā)送文件類型數(shù)據(jù)
print(r.text)
上傳文件接口
def test_post_upload_file(pub_data):
# post請求上傳文件
data = {
"file": open("aa.xls","rb")
}
h = {"token": pub_data["token"]}
r = requests.post("http://qa.yansl.com:8084/product/uploaProdRepertory", files=data, headers=h) # files關(guān)鍵字發(fā)送文件類型數(shù)據(jù)
print(r.text)
下載文件接口
def test_get_file(pub_data):
# get請求下載文件
p = {"pridCode":"63803y"}
h={"token":pub_data["token"]}
r = requests.request("GET","http://qa.yansl.com:8084/product/downProdRepertory",params=p,headers=h)
# r.content獲取響應(yīng)正文的字節(jié)碼(二進制)
with open("aa.xls","wb") as f: # with語法 打開文件,并賦值給變量f
f.write(r.content) # 把響應(yīng)中的數(shù)據(jù)寫入到文件中