2 python requests
1 安装
- pip install requests
2 requests.session
- http协议本身是无状态的,为了让请求之间保持状态,有了session和cookie机制。requests也提供了相应的方法(session)去操纵它们。
3 发送 get 请求
import requests session = requests.session() # 保持session host = 'http://127.0.0.1:9090' # 服务端地址 path = '/' # 请求路径 headers = {} # 请求头,get 可以为空 params = {} # 请求体,没有可以为空 resp = session.get(url=host+path, headers=headers, data=params) # 发送 get 请求 resp.status_code # 获取状态码 resp.text # 获取返回的字符串
4 发送 post 请求
import requests session = requests.session() host = 'http://127.0.0.1:9090' path = '/post/json' headers = { "Content-Type": "application/json;charset=UTF-8" } params = { 'username': 'lizi_json', 'password': '123456' } resp = session.post(url=host+path, headers=headers, json=params) resp.status_code resp.json() # 获取返回的 json