Python接口测试实战2 - 使用Python发送请求
https://www.cnblogs.com/superhin/p/10338930.html
# -*- coding:utf-8 -*- import requests import json hosts = "http://127.0.0.1:8082" #普通的get请求 def requestGet(): url = hosts+"/pinter/com/getSku?" params = {"id":1} get = requests.get(url=url,params=params) print(get.text) # print(res.json()) status_code = get.status_code codeData1 = get.json()["code"] message = get.json()["message"] if status_code == 200 and codeData1 == "0" and message == "success": print("success ") else: print("fail!")
{"code":"0","message":"success","data":{"skuId":1,"skuName":"ptest-1","price":"310","stock":481,"brand":"testfan"}}
success
#普通的post请求 def requesPost(): url = hosts + "/pinter/com/login" data = {"userName":"admin","password":"1234"} post = requests.post(url=url,data=data) print(post.text) # print(post.headers)
{"code":"0","message":"success","data":null}
#值为json的 def requesPost2(): url = hosts + "/pinter/com/buy" data = {"param":{"skuId":123,"num":10}} post = requests.post(url=url,data=data) print(post.text) print(post.headers)
{"code":"0","message":"success","data":"num,skuId"}
{'Date': 'Sun, 18 Apr 2021 12:48:15 GMT', 'Transfer-Encoding': 'chunked', 'Content-Type': 'application/json;charset=UTF-8'}
#参数为josn的接口 def requesPost3(): url = hosts + "/pinter/com/register" data = {"userName":"test","password":"1234","gender":1,"phoneNum":"110","email":"beihe@163.com","address":"Beijing"} headers = {"Content-Type":"application/json"} post = requests.post(url=url,data=json.dumps(data),headers=headers) print(post.text) print(post.headers)
{"code":"0","message":"注册成功","data":null}
{'Date': 'Sun, 18 Apr 2021 12:48:15 GMT', 'Transfer-Encoding': 'chunked', 'Content-Type': 'application/json;charset=UTF-8'}
if __name__ == '__main__': # requestGet() # requesPost() # requesPost2() requesPost3()
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步