Python http client及server

这两天刚好在用http服务,百度了好久,大部分案例都是单独搭建http server或者client的。

我这里把自己调通的代码贴上来,供自己和需要的小伙伴们备忘。

http server:

from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import urllib

data = {
    'result': 'this is a test',
    'RSP_HEAD': {'TRAN_SUCCESS': '1'}, 
    'RSP_BODY': {
        'rspCode': '200',
        'pid': 'CN11048023010321250000030000010',
        'CFCNO': '03',
        "AgentNo": "03",
        "PIDSts": "30",
        }
    }
host = ('localhost', 8888)


class Resquest(BaseHTTPRequestHandler):
    def do_GET(self):
        print("to get something......")
        d = self.headers
        # get_data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))
        print(d)
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode('utf-8'))

    def do_POST(self):
        print("to parse post......")
        length = int(self.headers['Content-Length'])
        post_data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))
        # You now have a dictionary of the post data
        print(post_data)
        # self.wfile.write("Lorem Ipsum".encode("utf-8"))
        self.send_response(200)
        # self.send_response(404)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode('utf-8'))


if __name__ == '__main__':
    server = HTTPServer(host, Resquest)
    print("Starting server, listen at: %s:%s" % host)
    server.serve_forever()

运行后:

Starting server, listen at: localhost:8888

 

client:

import logging_demo
import requests
import json
import urllib.request
import os

def test_post():
    conn = requests.session()
    # url = 'http://www.gsdata.cn/member/login'
    url = 'http://localhost:8888'
    postdata = {
        "PID": "1234561213141314334534535636356",
        "CARDNO": "6222623434343465645",
        "PST_CDE": "200000",
        "PST_ADR":"shanghia chuanshan ybocomm 13232 room",
        "PNM":"Lin Zhen",
        "MOB_NUM":"13332333445",
    }
    headers = {'content-type': "application/json", 'Authorization': 'APP appid = 4abf1a,token = 9480295ab2e2eddb8'}
    rep = conn.post(url, data=postdata, headers=headers)
    print(rep.text)


if __name__ == "__main__":
    # post_info()
    # psot_info_3()
    test_post()

当运行客户端后:python C:\Users\http_clent_demo.py

server 收到client的POST请求:

to parse post......
{'PST_ADR': ['shanghia chuanshan ybocomm 13232 room'], 'PID': ['1234561213141314334534535636356'], 'PNM': ['Lin Zhen'], 'MOB_NUM': ['13332333445'], 'CARDNO': ['6222623434343465645'], 'PST_CDE': ['200000']}
127.0.0.1 - - [22/Jul/2019 22:43:50] "POST / HTTP/1.1" 200 -

server 向client 返回200,同时返回一起其他报文data

{"result": "this is a test", "RSP_HEAD": {"TRAN_SUCCESS": "1"}, "RSP_BODY": {"AgentNo": "03", "CFCNO": "03", "rspCode":
"200", "PIDSts": "30", "pid": "CN11048023010321250000030000010"}}

 

以上是参考百度上各位小伙伴们分享的代码,自己组装到一块,分享给大家。

如有不妥之处,请大家留言,我很乐意学习~~

谢谢!

 

你可能感兴趣的:(Python基础编码)