requests库:python来发送http请求。(用代码带起postman的操作)
requests 下载
pip install requests
request 的基础操作
先导包。
import request
输入地址
url = "https://www.baidu.com"
发送请求
res = requests.get(url=url)
打印结果
print(res.text)
或::
url = "https://www.baidu.com/"
# 发送请求
res = requests.get(url=url)
data = res.text
li = data.encode("utf-8")
print(li.decode())
简单使用:
import requests
# 请求头
header = {
"Authorization":‘Bearer d7e4534c-533f-4251-881f-1c2136842d5c‘,
"Content-Type":"application/json"
}
# 请求路径
url = "http://localhost:8080/api/sys/user"
# 请求的参数
data = {
"page":1,
"size":3
}
# 发送请求,headers是请求头的数据,params是请求所携带的参数
res = requests.get(url=url,headers = header,params=data)
print(res)
# 拿数据
res_data = res.json()
print(res_data)
简单使用
requests 的状态保持使用(1.登录 2.状态保持后展示数据)
import requests,json
def fun1():
URL = "http://localhost:8080/api/sys/login"
data = {
"mobile":"13800000001","password":"123436"
}
json_data = json.dumps(data)
deader = {
"Content-Type":"application/json"
}
res = requests.post(url=URL,data=json_data,headers=deader)
res_data= res.json()
token = res_data["data"]
print( token )
new_token = "Bearer "+token
new_deader = {
"Authorization": new_token ,
"Content-Type": "application/json"
}
# 请求路径
url = "http://localhost:8080/api/sys/user"
# 请求的参数
data = {
"page": 1,
"size": 3
}
# 发送请求
res = requests.get(url=url, headers=new_deader, params=data)
res_data =res.json()
print(res_data)
if __name__ == ‘__main__‘:
fun1()