I made a simple script that performs POST http calls to an api by having it bode encoded as Json:
#!/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
But I get the following error:
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
And I cannot figure out why. I tried to do anything I can think of but I fail.
Just remove the:
conn.putheader("Content-Type",'application/json')
Line from your code. By passing the headers object to the httplib.request
method is just enough.