用Python进行快速网络接口测试,比用curl或者Paw之类的工具还方便。
import requests
import os
import json
base = 'http://httpbin.org/'
cookie = 'da0d9b016a754a2b769cf1940686ff7f'
def get(url, params=None, method='get'):
url = url.lower()
if not (url.startswith('http://') or url.startswith('https://')):
url = os.path.join(base, url)
print(url)
try:
if method == 'get':
response = requests.get(
url=url,
headers={
"Content-Type": "application/json",
'Cookie': cookie
},
params=params
)
else:
if isinstance(params, dict):
params = json.dumps(params)
response = requests.post(
url=url,
headers={
"Content-Type": "application/json",
'Cookie': cookie
},
data=params
)
print('Response HTTP Status Code: {status_code}'.format(
status_code=response.status_code))
print('Response HTTP Response Body: {content}'.format(
content=response.content))
except requests.exceptions.RequestException:
print('HTTP Request failed')
def post(url, params=None):
get(url, params, 'post')
if __name__ == '__main__':
d = {'hello': 'world'}
get('get')
get('get', d)
post('post')
post('post', d)