当调用自定义api pythons时出错了httplib.CannotSendHeader异常

时间:2017-06-16 06:48:33

标签: python httplib

我制作了一个简单的脚本,通过将其编码为Json来对api执行POST http调用:

#!/usr/bin/python
# coding: utf-8

import sys
import httplib
from base64 import b64encode
from json import dumps

filename = sys.argv[1]
outfile = filename + ".txt"
with open(filename, 'rb') as f:
    content = f.read()

data = b64encode(content)

jsonData = {
    'param_1': 12,
    'param_2': 12,
    'filename': "45.jpg",
    'file_data': data
}

jsonData = dumps(jsonData)

headers = {
    "Content-Type": 'application/json',
    "Accept": '*/*'
}

conn = httplib.HTTPConnection('localhost',8016)
conn.putheader("Content-Type",'application/json')
conn.sendheaders()

conn.request('POST', '/files', jsonData, headers)

response = conn.getresponse()
print response

但是我收到以下错误:

Traceback (most recent call last):
  File "./add_file.py", line 31, in <module>
    conn.putheader("Content-Type",'application/json')
  File "/usr/lib/python2.7/httplib.py", line 1026, in putheader
    raise CannotSendHeader()
httplib.CannotSendHeader

我无法弄清楚原因。我试着做任何我能想到的事情,但我失败了。

1 个答案:

答案 0 :(得分:0)

只需删除:

conn.putheader("Content-Type",'application/json')

代码行。通过将headers对象传递给httplib.request方法就足够了。