用Python实现一个http server
# python2# coding = utf-8from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandlerimport jsonclass 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-8import jsonimport urllib2data = { '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())
# python3# coding = utf-8import requestsmydict = { 'key1': 'value1', 'key2': 'value2'}r = requests.post("host:port/post", json=mydict)print(r.status_code)print(r.json())