使用http://httpbin.org测试,一个简单的 HTTP 请求和响应服务。(需联网)
1.导入requests包
import requests
2.测试get请求
url = 'http://httpbin.org/get'
par = {'key1': 'value1', 'key2': 'value2'}
# 不带参数请求
r1 = requests.get(url)
# 带参数请求
r2 = requests.get(url, params=par)print(r2.text)
返回结果
3.测试post请求,字典传参
# 测试post请求,字典传参
url1 = 'http://httpbin.org/post'
data = {'key1': 'value1', 'key2': 'value2'}
res = requests.post(url1, data=data)
print(res.text)
返回结果
4.测试post请求,json传参
# 测试post json传参
url1 = 'http://httpbin.org/post'
json = {'keys': {'key1': 'value1', 'key2': 'value2'}
}
res1 = requests.post(url1, json=json)
print(res1.text)
返回结果
5.测试post请求,文件传参
# 文件上传,需先打开再上传,rb为二进制模式读取
url1 = 'http://httpbin.org/post'
upload_files = {'files': open('request_post.py', 'rb')
}
res2 = requests.post(url=url1, files=upload_files)
print(res2.status_code)
print(res2.text)
返回结果