1. 上传文件
先看下requests库中的官方描述
用charles抓包,请求头如下:
请求体如下:
用fiddler抓包,如下:
构造post请求,代码如下:
header中不要加Content-Type
url = 'https://main.test.com/storage/1/storage?dir=abc'
file = {
'file': open('/Users/zhangyang/PycharmProjects/untitled/image/yinzhang.png', 'rb')
}
header = { # python调用java传文件接口,需要去掉Content-Type(猜测是python和java接口的兼容问题)
'token': token
}
ret = requests.post(url=url, files=file, headers=header, verify=False)
pprint(ret.json())
按照上面官方文档的描述,files参数还可以如下:
file = {
'file': ('yinzhang.png', open('/Users/zhangyang/PycharmProjects/untitled/image/yinzhang.png', 'rb'))
}
还可以如下:
file = {
'file': ('yinzhang.png', open('/Users/zhangyang/PycharmProjects/untitled/image/yinzhang.png', 'rb'), 'image/png')
}
2. 下载文件
先找到文件下载请求链接,代码如下:
示例1:
download_url = 'https://main-test.3hea.com/web/1/report/' # 下载链接
ret = requests.get(url=download_url, headers=header)
with open('aaa.xlsx', 'wb') as f: # 将返回的数据写入文件
示例2:
d_url ='http://a.test.com/app/abccc.apk'
ret = requests.get(d_url)
with open('abc.apk', 'wb') as f:
f.write(ret.content)