首页 > 编程语言 > 详细

python http server handle json

时间:2017-08-07 21:22:41      阅读:205      评论:0      收藏:0      [点我收藏+]

用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

原文:http://www.cnblogs.com/gattaca/p/7301282.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!