python创建httpserver,并处理get、post请求

参考:
https://blog.csdn.net/gujing001/article/details/53152793/

搭建一个简单的httpserver,用于测试数据通讯

from http.server import HTTPServer, BaseHTTPRequestHandler
import json

data = {'result': 'this is a test'}
host = ('localhost', 8888)


class Resquest(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode())

    def do_POST(self):
        datas = self.rfile.read(int(self.headers['content-length']))

        print('headers', self.headers)
        print("do post:", self.path, self.client_address, datas)

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

Qt这边可以这样子操作:


QNetworkAccessManager man;
void MainWindow::on_pushButton_clicked()
{
    QNetworkReply *mReply;

    QNetworkRequest request;
    request.setUrl(QUrl("http://127.0.0.1:8888"));

//    mReply = man.get(request);
//    connect(mReply, &QNetworkReply::finished, [=](){
//       qDebug() << "get these:" << mReply->readAll();

//       mReply->deleteLater();
//    });

    uchar tmpData[] = {0x12, 0x03, 0x04, 0x05, 0x06};
    QByteArray ba((const char*)tmpData, sizeof(tmpData));

    request.setUrl(QUrl("http://127.0.0.1:8888/abc/def"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "text");
    request.setRawHeader("self_defined_heade", "789456");
    mReply = man.post(request, ba);
    connect(mReply, &QNetworkReply::finished, [=](){
       qDebug() << "post finished:" << mReply->readAll();

       mReply->deleteLater();
    });


    qDebug() << "-----------------";
}

你可能感兴趣的:(python,python,http)