requests包下几种常见请求方法以及参数的使用

导入requests包

import requests

http请求构造
发送一个get请求

res = requests.get(“http://httpbin.org”)

发送一个post请求

res = requests.post(‘http://httpbin.org/post’,json={‘k’:‘v’})

发送一个put请求

res = requests.put(‘http://httpbin.org/put’,json={‘k’:‘v’})

发送一个delete请求

res = requests.delete(‘http://httpbin.org/delete’,json={‘k’:‘v’})

发送一个options 请求

res = requests.options(‘http://httpbin.org/get’)

发送一个head 请求

res = requests.head(‘http://httpbin.org/get’)

获取回应的状态码

print(res.status_code)

获取回应的包头

print(res.headers)

获取回应的内容体

print(res.text)

也可以直接使用 request 函数,传入不同的方法
发送get请求

res = requests.request(‘get’,“http://httpbin.org”)

发送post请求

res =requests.request(‘post’,“http://httpbin.org/post”,json={‘k’:‘v’})

发送put请求

res =requests.request(‘put’,“http://httpbin.org/put”,json={‘k’:‘v’})

发送delete请求

res =requests.request(‘delete’,“http://httpbin.org/delete”,json={‘k’:‘v’})

--------------------------------------------------
verify参数(默认为ture)False为忽略对 SSL 证书的验证

res =requests.request(‘delete’,“http://httpbin.org/delete”,verify=False)

proxies参数,设置代理,可以分别设置 HTTP 请求和 HTTPS 请求的代理。

px = {
‘http’: ‘http://10.10.1.10:3128’,
‘https’: ‘http://10.10.1.10:1080’,
}
requests.get(‘https://api.github.com/events’, proxies=px)

allow_redirects 参数,控制是否启用重定向,True 为启用,False 为禁用

res = requests.get(‘http://github.com’, allow_redirects=False)
print(r.status_code)

timeout参数,设定超时时间

res = requests.get(‘http://github.com’, timeout=0.001)
注意:timeout 仅对连接过程有效,与响应体的下载无关。timeout 并不是整个下载响应的时间限制,而是如果服务器在 timeout 秒内没有应答,将会引发一个异常(更精确地说,是在 timeout 秒内没有从基础套接字上接收到任何字节的数据时),如果不设置 timeout,将一直等待。

files 参数,上传文件,dict 格式

files = {‘file’: open(‘report.xls’, ‘rb’)}
res = requests.post(‘http://httpbin.org/post’, files=files)

header 参数,通过传入 dict 定制请求头

headers = {‘user-agent’: ‘my-app/0.0.1’}
res = requests.get(‘https://api.github.com/some/endpoint’, headers=headers)

data 参数,发送编码为表单形式的数据单

ddd = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
res = requests.post(“http://httpbin.org/post”, data=ddd)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值