首页 > 代码库 > python http server handle json
python http server handle json
用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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。