导读
有些时候我们需要使用Python来模拟curl发送请求获取,响应的结果,在这篇文章中,我们将介绍如何在Python3中通过使用urllib3来获取请求的响应结果
urllib3
urllib3可以模拟HTTP和HTTPS的post以及get请求
- 安装
在Python3的版本中,应该默认安装了这个模块,如果没有安装,请使用下面的命令进行安装
pip install urllib3
- 不带参数的get请求
import urllib3
http = urllib3.PoolManager()
#发起一个GET请求并且获取请求的响应结果
r = http.request('GET', 'http://httpbin.org/robots.txt')
#输出响应的数据
print(r.data)
- 带参数的POST请求
r = http.request('POST','http://httpbin.org/post',fields={'hello': 'world'})
- 带json数据的传参
#定义一个字典类型的参数数据
data = {'attribute': 'value'}
#将字典数据编码为json数据
encoded_data = json.dumps(data).encode('utf-8')
#发送一个body的json数据
r = http.request('POST','http://httpbin.org/post',body=encoded_data,
headers={'Content-Type': 'application/json'})
#对响应的数据解码为json数据
json.loads(r.data.decode('utf-8'))['json']
- body带二进制的数据的传参
with open('example.jpg', 'rb') as fp:
binary_data = fp.read()
r = http.request('POST','http://httpbin.org/post',body=binary_data,
headers={'Content-Type': 'image/jpeg'})
json.loads(r.data.decode('utf-8'))['data']
- form-data传输文件数据
with open('example.txt') as fp:
file_data = fp.read()
r = http.request('POST','http://httpbin.org/post',fields={'filefield': ('example.txt',file_data),})
json.loads(r.data.decode('utf-8'))['files']