调用自定义 api pythons 时抛出错误 httplib.CannotSendHeader 异常
When calling to custom api pythons thows error httplib.CannotSendHeader exception
我制作了一个简单的脚本,通过将其编码为 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
而且我不明白为什么。我尝试做任何我能想到的事情,但我失败了。
只需删除:
conn.putheader("Content-Type",'application/json')
您的代码行。通过将 headers object 传递给 httplib.request
方法就足够了。
我制作了一个简单的脚本,通过将其编码为 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
而且我不明白为什么。我尝试做任何我能想到的事情,但我失败了。
只需删除:
conn.putheader("Content-Type",'application/json')
您的代码行。通过将 headers object 传递给 httplib.request
方法就足够了。