python3–post请求时Content-Type类型的注意事项

当我们在日常自动化测试中遇到接口测试–post请求且带有参数时(参数不带文件的情况),我们会在header上附带定义好的content-type,一般情况下都是:application/json,如下所示:
header = {
‘Connection’: ‘keep-alive’,
‘Accept-Language’: ‘zh-CN,zh;q=0.9’,
’Content-Type’: 'application/json’
}
此时,使用requests库做请求时:res = requests.post(url=url, headers=header, data=data)
系统会正常返回post请求的结果,我们用result = res.json()可以得到对应返回内容。

但当我们做post请求且附带文件(也就是做上传文件操作),且是二进制文件时,需要特别注意两点

1.将我们要上传的文件写为:files = {“file”: open(‘E:\test.xls’, “rb”)}
这一步是为了把我们要上传的文件作为files参数传给request请求。

2.将我们在header里写的’Content-Type’: 'multipart/form-data’去掉或者注释掉
这一步,我们通常习惯性地认为,此时需要在header里把content-type设置为:multipart/form-data,因为我们抓包或者在浏览器直接通过F12拿到的接口请求里,content-type = multipart/form-data,写的清清楚楚,所以我们将header设为如下情况:
header = {
‘Connection’: ‘keep-alive’,
‘Accept-Language’: ‘zh-CN,zh;q=0.9’,
’Content-Type’: 'multipart/form-data’
}
但此时你去做post请求,res = requests.post(url=url, headers=header, data=data,files=files)
系统会报错,这是因为request请求在做post请求时会自动加上Content-Type: multipart/form-data;boundary=${bound},而我们在header里设置的并没有关键标识boundary,因此我们只需在header里注释掉原有的 ‘Content-Type’: ‘multipart/form-data’,让request请求自动添加即可。此时再像之前一样做post请求,
res = requests.post(url=url, headers=header, data=data,files=files)
系统请求正常,返回接口请求结果。

更多推荐

python3--post请求时Content-Type类型的注意事项