python http server handle json
阿新 • • 發佈:2017-08-07
run cat headers post data host p s list from write
用Python實現一個http server
# python2 # coding = utf-8 from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler import json class RequestHandler(BaseHTTPRequestHandler): def _set_headers(self): self.send_response(200) self.send_header(‘Content-type‘, ‘application/json‘) self.end_headers()def do_GET(self): response = { ‘status‘:‘SUCCESS‘, ‘data‘:‘hello from server‘ } self._set_headers() self.wfile.write(json.dumps(response)) def do_POST(self): content_length = int(self.headers[‘Content-Length‘]) post_data = self.rfile.read(content_length)print ‘post data from client:‘ print post_data response = { ‘status‘:‘SUCCESS‘, ‘data‘:‘server got your post data‘ } self._set_headers() self.wfile.write(json.dumps(response)) def run(): port = 80 print(‘Listening on localhost:%s‘ % port) server = HTTPServer((‘‘, port), RequestHandler) server.serve_forever() run()
python post json
# python2 # coding = utf-8 import json import urllib2 data = { ‘key1‘:‘value1‘, ‘key2‘:‘value2‘ } req = urllib2.Request(‘http://server_ip:server_port‘) req.add_header(‘Content-Type‘, ‘application/json‘) response = urllib2.urlopen(req, json.dumps(data)) print(response.read())
python http server handle json