接口測試-POST請求(七)


一、簡介

學習requests模塊,是讓大家去訪問官方網站,查看官方文檔;其實學習一個新的模塊捷徑,不用去百度什么的,直接用 help 函數就能查看相關注釋和案例內容。

print(help(requests))

  

二、POST請求案例,數據為dict格式

url = 'http://httpbin.org/post'
datas = {'key1':'value1','key2':'value2'}

#dict參數請求
p=requests.post(url,data=datas)
print(p.text)
print(p.status_code)

  

三、POST請求案例,數據為json格式

注意這里需要把dict轉換成json數據格式

json_data = json.dumps(datas)

  

post請求參考

url = 'http://httpbin.org/post'
datas = {'key1':'value1','key2':'value2'}

json_data = json.dumps(datas)
#json請求
p=requests.post(url,json=json_data)
print(p.text)
print(p.status_code)

  

四、添加請求頭header

現在由於對接口安全性的要求,使得模擬登錄越來越復雜,比上邊介紹的基本內容要復雜很多。一般來說登陸只要涉及安全性方面考慮,那么登陸就會比較復雜。

1、以博客園為例,幾年前模擬登陸,沒有涉及安全性考慮相對簡單。發展到現在其登錄涉及安全性考慮,所以實際的情況要比上面講的幾個復雜很多,

2、我們在請求數據時也可以加上自定義的headers(通過headers關鍵字參數傳遞)有時候有的特殊的請求必須加上headers頭信息,才回返回響應結果。例如:博客園登錄時,將請求頭 headers添加上,這里不是說博客園登錄必須登錄才能返回

響應結果,而是以其為例子來說明將請求頭header參數加入到登錄請求接口中

2.1 抓包,查看其請求頭,或者瀏覽器F12,接口查看對應header

 

 

 

 參考代碼:

url = 'http://httpbin.org/post'
datas = {'key1':'value1','key2':'value2'}
#header,以字典形式傳入
headerst = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'}
json_data = json.dumps(datas)
#json請求
p=requests.post(url,headers=headerst,json=json_data)
print(p.text)
print(p.status_code)

  

 

遇到問題報錯和解決辦法:

報錯:

raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='httpbin.org', port=443): Max retries exceeded with url: /post (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))

 解決辦法:

1、由於這里是 https 請求,直接發送請求會報錯誤:SSLError: HTTPSConnectionPool(host='httpbin.org', port=443): Max retries exceeded with url: /post (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))

2、可以加個參數:verify=False,表示忽略對 SSL 證書的驗證,但是此時仍然會有警告:

InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)

3、這里請求參數 payload 是 json 格式的,用 json 參數傳。將請求頭寫成字典格式,進行傳參。

4、最后結果是 json 格式,可以直接用 r.json 返回 json 數據:

{'args': {}, 'data': '', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '0', 'Host': 'httpbin.org', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'}, 'json': None, 'origin': '222.128.10.95, 222.128.10.95', 'url': 'https://httpbin.org/post'}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM