Skip to main content
 首页 » 编程设计

Python 'requests' 模块和编码

2025年05月04日9lonelyxmas

我正在使用请求模块执行一个简单的 POST 请求,并根据 httpbin 对其进行测试

import requests 
 
url      = 'http://httpbin.org/post' 
params   = {'apikey':'666666'} 
sample   = {'sample': open('test.bin', 'r')} 
 
response = requests.post( url, files=sample, params=params, verify=False) 
report_info = response.json() 
print report_info 

我的编码有问题。它没有使用 application/octet-stream,因此编码不正确。从标题中,我看到:

{ 
  u'origin': u'xxxx, xxxxxx',  
  u'files': { 
               u'sample': u'data:None;base64,qANQR1DBw.......... 

因此,当我尝试使用 curl 时,我得到的是 data:None 而不是 data:application/octet-stream。文件大小和编码不正确。

我如何强制或检查它是否正在使用 application/octet-stream?

请您参考如下方法:

样本取自 http://www.python-requests.org/en/latest/user/quickstart/#custom-headers

>>> import json 
>>> url = 'https://api.github.com/some/endpoint' 
>>> payload = {'some': 'data'} 
>>> headers = {'content-type': 'application/json'} 
 
>>> r = requests.post(url, data=json.dumps(payload), headers=headers) 

您可能希望将 headers 更改为

headers = {'content-type': 'application/octet-stream'} 
response = requests.post( url, files=sample, params=params, verify=False, 
             headers = headers)