如何读取API返回的application/octet-stream类型文件内容?
解决Python获取application/octet-stream类型API内容的问题
根据你提供的请求头和代码,你使用的应该是urllib3库的连接池发送请求,这类请求返回的HTTPResponse对象并没有.data属性,正确获取二进制内容的方式是调用.read()方法:
正确代码示例
# 发送POST请求 response_returned = https.request(method='POST', url=f'{Checker}/Id/Document/', headers=headers, body=body) # 读取二进制响应内容 binary_content = response_returned.read() # 可选:将内容保存为文件(比如请求头指定的PDF) with open('Document.pdf', 'wb') as file: file.write(binary_content)
额外说明
- 为什么
.data不生效:urllib3的HTTPResponse对象没有.data属性,必须通过.read()方法读取二进制流内容,该方法返回的字节串正好匹配application/octet-stream类型的数据。 - 解析响应头中的文件名:如果需要自动获取请求头里的文件名,可以解析
Content-Disposition字段:
from urllib.parse import unquote content_disposition = response_returned.headers.get('Content-Disposition') if content_disposition and 'filename=' in content_disposition: filename = content_disposition.split('filename=')[1].strip('"') filename = unquote(filename) print(f"获取到文件名: {filename}") # 用获取到的文件名保存文件 with open(filename, 'wb') as file: file.write(binary_content)
内容的提问来源于stack exchange,提问作者Baba
相关产品推荐
相关产品推荐

