Python3模拟curl发送请求

导读

有些时候我们需要使用Python来模拟curl发送请求获取,响应的结果,在这篇文章中,我们将介绍如何在Python3中通过使用urllib3来获取请求的响应结果

urllib3

urllib3可以模拟HTTPHTTPSpost以及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']

参考:https://urllib3.readthedocs.io/en/latest/user-guide.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

修炼之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值