python-requests库发送http-POST&GET包
任务主要是使用requests库来实现和命令行curl指令发包一样的功能
其中有一些技术细节:
curl的一些参数
—location参数,用于指定跟随服务器的重定向,在requests中,默认的post和get等方法都是自动跟随服务器重定向的,但是要想关闭的话可以将参数allow_redirects=设置为FALSE
-k参数,用于关闭对服务器ssl证书的验证,在post和get方法中,关闭验证需要设置verify=参数为FALSE,可能需要关闭该warning:from requests.packages.urllib3.exceptions import InsecureRequestWarningrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)
类比发包方法
curl —request POST —url https://open.workec.com/auth/accesstoken —header ‘cache-control: no-cache’ —header ‘content-type: application/json’ —data ‘{ “appId”: appId, “appSecret”: “appSecret”}’
类似的python 发包方法就是
import requestsheaders = {
‘cache-control’: ‘no-cache’,
‘content-type’: ‘application/json’,
}
data = ‘{\t”appId”: appId,\t”appSecret”: “appSecret”}’
response = requests.post(‘https://open.workec.com/auth/accesstoken’, headers=headers, data=data)
也有在线工具的链接:https://curl.trillworks.com
返回对象response
可以通过response来获取status_code
content属性是响应内容的二进制字节串,text则是文本字符串
可以根据约定的type或者Context-type属性,将其转化为对应的格式
字节流下载
当响应文件很大时,需要采用字节流分chunk下载requests.adapters.DEFAULT_RETRIES = 5response = requests.get(url, stream=True)status = response.status_code if status == 200:total_size = int(response.headers['Content-Length'])with open('xxx', 'wb') as of:for chunk in response.iter_content(chunk_size=102400):if chunk:of.write(chunk)
