I want to send and receive some simple data over HTTP.
Here's the server side:
import time
import BaseHTTPServer
import json
HOST_NAME = 'localhost'
PORT_NUMBER = 9000
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_POST(self):
print "You've got mail!"
content_len = int(self.headers.getheader('content-length', 0))
body = self.rfile.read(content_len)
data = json.loads(body)
print data
if __name__ == '__main__':
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME,
PORT_NUMBER)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
Here's the client side:
import requests
import json
url = 'http://localhost:9000'
data = {
'date': 'the best day',
'time': 'the best time',
'name': 'Janet Smith'
}
r = requests.post(url, json=data)
print r.status_code
print r.json()
I'm getting this error:
Traceback (most recent call last): File "testSend.py", line 17, in
r = requests.post(url, json=data)
File "/Library/Python/2.7/site-packages/requests/api.py", line 116, in post return request('post', url, data=data, json=json, **kwargs)
File "/Library/Python/2.7/site-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/Library/Python/2.7/site-packages/requests/sessions.py", line 524, in request
resp = self.send(prep, **send_kwargs)
File "/Library/Python/2.7/site-packages/requests/sessions.py", line 637, in send
r = adapter.send(request, **kwargs)
File "/Library/Python/2.7/site-packages/requests/adapters.py", line 498, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.',
BadStatusLine("''",))
EDIT: I was originally experiencing a server-side error as well, but looks like the issue might have been with a line of pasted code. I re-indented everything and now it works.
Turns out there were several problems:
The server side error was due to copy pasting code. I needed to re-indent everything.
The client side error was fixed by adding self.send_response(200) to my DO_POST function on the server side
Doing #2 introduces a new "cannot decode json" error. This is because the response from the server does not contain a json message. So I just need to comment out the print r.json() line or send a json message on the server side.