python 3接口测试
Post方式:
urllib库
# coding:utf-8
import urllib.parse
import urllib.request
url = 'http://***/api/OverdueInfo/OverdueOrderInfo'#接口地址
# values的形式:name:value
values = {"BusinessID": '887100'}
# 使用urllib.urlencode函数对values字典进行处理,最终形式为:**=***&**=***
data = urllib.parse.urlencode(values).encode(encoding='utf-8') #编码成utf-8
# 如果对data顺序有要求,建议自己拼接data
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
the_page = response.read().decode('utf-8') #解码成utf-8
print(the_page)
requests库
import requests
bid = '1283227'
status = '3'
payload = {"BusinessID": bid,
"LawsuitStatus": status,
"LawsuitCost": '200',
"LawsuitLiquidatedDamages": '2000',
"LawsuitCode": "ssh",
"UserId": '18374'
}
r = requests.post('http://10.138.***:8080/api/LawsuitOption/LawsuitResultSynch', data=payload)
print(r.text)
有时候我们需要传送的信息不是表单形式的,需要我们传JSON格式的数据过去,所以我们可以用 json.dumps() 方法把表单数据序列化。
import requests
import json
bid = '1283227'
status = '3'
payload = {"BusinessID": bid,
"LawsuitStatus": status,
"LawsuitCost": '200',
"LawsuitLiquidatedDamages": '2000',
"LawsuitCode": "ssh",
"UserId": '18374'
}
r = requests.post('http://10.138.***:8080/api/LawsuitOption/LawsuitResultSynch', data= json.dumps(payload))
print(r.text)
参数需要以json格式出入时:
import requests
bid = '1283227'
status = '3'
payload = {"BusinessID": bid,
"LawsuitStatus": status,
"LawsuitCost": '200',
"LawsuitLiquidatedDamages": '2000',
"LawsuitCode": "ssh",
"UserId": '18374'
}
r = requests.post('http://10.138.***:8080/api/LawsuitOption/LawsuitResultSynch', json= payload)
print(r.text)
Get方式:
urllib库
# coding:utf-8
import urllib.request
import urllib.error
url_save = 'http://www.baidu.com/'
try:
s_save = urllib.request.urlopen(url_save).read()
print(s_save)
except urllib.error.HTTPError as e:
print(e.code)
except urllib.error.URLError as e:
print(str(e))
requests库
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get",params=payload)
print (r.url)
参考地址:
http://blog.csdn.net/liuchunming033/article/details/45538205
http://cuiqingcai.com/2556.html