Skip to content

Instantly share code, notes, and snippets.

@vermaslal
Created October 3, 2015 10:46
Show Gist options
  • Save vermaslal/a214f4be171a5ee646ba to your computer and use it in GitHub Desktop.
Save vermaslal/a214f4be171a5ee646ba to your computer and use it in GitHub Desktop.
Python code to create a HTTP post request and handle json request
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer
import simplejson
import random
class S(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
self._set_headers()
f = open("index.html", "r")
self.wfile.write(f.read())
def do_HEAD(self):
self._set_headers()
def do_POST(self):
self._set_headers()
print "in post method"
self.data_string = self.rfile.read(int(self.headers['Content-Length']))
self.send_response(200)
self.end_headers()
self.wfile.write('Action completed')
data = simplejson.loads(self.data_string)
print(data)
return
def run(server_class=HTTPServer, handler_class=S,host='localhost', port=8080):
server_address = (host, port)
httpd = server_class(server_address, handler_class)
print 'Starting httpd...'
httpd.serve_forever()
if __name__ == "__main__":
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment