学习python调用WebApi的基本用法(2)
使用requests库以post方式调用WebApi接口的方式类似于前文,但由于post方式通常由请求体传递json格式参数,其用于与get调用略有区别,主要注意点如下:
1)如果是https开头的地址,如果网站证书已经过期,需要设置verify属性为False(post或者get函数都需要设置),否则会报下面的错误:
requests.exceptions.SSLError: HTTPSConnectionPool(host='localhost', port=44303): Max retries exceeded with url: /EasyCaching/GetToken (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:997)')))
2)通过请求体传递json格式的参数,需要在调用post函数时设置data属性,且需调用json.dumps函数将字符串转换为json格式(需要安装并引入json库);
3)如果需要设置请求头,则在调用post函数时设置headers属性。
以之前编写的基于JWT的身份验证WebApi接口为例,首先调用GetToken函数获取JWT Token,然后将Token附在请求头中调用GetInfo函数,示例代码及运行结果如下所示:
import requests
import json url = 'https://localhost:44303/EasyCaching/GetToken'response = requests.get(url, verify=False)jwt_token=response.textdata={"UserName": "1","UserSex": "2","UserPassword": "3","IsKeyUser": True
}headers={'Authorization':'Bearer '+jwt_token,'Content-Type':'application/json'}url='https://localhost:44303/EasyCaching/GetInfo'result=requests.post(url,data=json.dumps(data),headers=headers, verify=False)result_json = result.json()
print('UserName:'+result_json['UserName'])
参考文献:
[1]https://api.vvhan.com/
[2]https://blog.csdn.net/weixin_41287260/article/details/146780908