1、python3.6 安装pip3 install requests
2、引用 import requests
3、HTTP请求总结:
1)session/requests使用方式,利用session 会回种cookie信息,会话保持测关联接口
import requests
session = requests.session() #会话保持测关联接口
r = session.get(url='http://www.baidu.com')
print(r.status_code)
2)直接发送,每次新建立链接
r2 = requests.get(url='http://www.baidu.com')
print(r2.status_code)
3)发送各种类型的http请求
1、get请求 无参数
r = requests.get( url = 'http://www.baidu.com')
print(r.text)
2、get请求 有参数 url地址栏后面 ?k=v&k1=v1
http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?op=getSupportCityString
params = {
'A': 123,'B':456}
r = requests.get(url='http://127.0.0.1/getInfo',params=params)
print(r.text)
print(r.status_code)
3、post请求 正文格式 form表单 url-encode, 参数k=v&k1=v1
Content-Type=application/x-www-form-urlencoded
host = 'http://127.0.0.1'
headers = {
"Content-Type": "application/x-www-form-urlencoded"}
r=requests.post(url=host+'/getInfo',headers=headers, data={
"A": 123})
print(r.text)
4、post请求 正文格式 Content-Type = application/xml或
Content-Type = text/xml
host = 'http://127.0.0.1'
headers = {
"Content-Type":"text/xml; charset=utf-8"}
xml = '''
string
'''
r = requests.post(url=host+'/getInfo', headers=headers, data=xml)
print(r.text)
print(r.status_code)
5、post请求 正文格式 json 纯文本格式raw
Content-Type = application/json
host = 'http://127.0.0.1:8000'
headers = {
'Content-Type':'application/json;charset=utf-8'}
r = requests.post(url= host + '/get/', headers=headers, json={
"A":111})
print(r.text)
6、post请求 正文格式 muilt-part ,form表单,file 不要加Content-Type
postman可以看到Content-Type = multipart/form-data
1)上传走表单
files = {
'file':open('11.txt','rb') }
res=requests.post(url='http://127.0.0.1:8000/uploadFile/',files=files)
print(res.text)```
```python
2)下载
res = requests.get(url='http://127.0.0.1:8000/export/?xx=2&xxx=222')
with open('./test.csv','wb') as f:
for chunk in res.iter_content(1024): #每1024下载
f.write(chunk)```
7、关于session的使用
#1. 重定向禁止 allow_redirects=False,才可以取到cookie
第一个请求,取到对应的cookie
headers = {
'Content-Type' : 'application/x-www-form-urlencoded'}
res = requests.post(url= 'http://127.0.0.1:9000/login/',
headers=headers,data={
"username":"111","password":"111"},
allow_redirects=False)
token = res.cookies['token']
第二个请求使用
headers="Content-Type":"application/json","Cookie":"token="+token}
r=requests.post(url='http://127.0.0.1:9000/get/',headers=headers,json={
"month":"2"})
print(r.json())
#2、单token认证 login在响应里返token
第一个请求,取到对应的token
headers = {
'Content-Type' : 'application/json'}
r = requests.post(url= 'http://127.0.0.1:9000/login',
headers=headers,
json={
"password": "111","username": "111"})
token = r.json()['token']
第二个请求使用
r2 = requests.get(url='http://127.0.0.1:9000/info', headers={
"Authorization": "Bearer "+token})
print(r2.text)```
8、超时 默认等3秒
#接口测试中如何减少误报率:加timeout 失败重试机制
```python
for i in range(0,3):
try:
r = requests.get(url='http://127.0.0.1:9000/info', timeout=3)
break
except:
print('失败重试')
else:
raise Exception('失败三次,接口异常')