在Qt中使用QtWebApp搭建HTTP服务器

第一步 下载QtWebApp导入工程中

工程示例:

在这里插入图片描述

第二步 编写配置文件WebApp.ini

host=192.168.255.128	;服务ip地址
port=8080				;端口号
minThreads=4			;4个线程始终保持运行状态
maxThreads=100			;并发工作线程的最大数量
cleanupInterval=60000
readTimeout=60000
maxRequestSize=16000
maxMultiPartSize=10000000

第三步 加载配置文件,创建HTTP侦听器对象

main.cpp

#include "httplistener.h"
#include "httprequesthandler.h"
#include "RequestMapper.h" //自定义类请求映射器类

    QSettings* listenerSettings=
            new QSettings(QCoreApplication::applicationDirPath()+"/WebApp.ini",QSettings::IniFormat);
    new stefanfrings::HttpListener(listenerSettings, new RequestMapper());

第四步 自定义类请求映射器类

RequestMapper.h

#ifndef REQUESTMAPPER_H
#define REQUESTMAPPER_H
#include "httprequesthandler.h"
using namespace stefanfrings;

#include "HelloController.h"

class RequestMapper:public HttpRequestHandler
{
public:
    RequestMapper();
    void service(HttpRequest& request, HttpResponse& response);


private:
    HelloController m_helloController;

};

#endif // REQUESTMAPPER_H

RequestMapper.cpp

#include "RequestMapper.h"
#include "json.hpp"
#include <string>
using namespace std;
using namespace nlohmann;
RequestMapper::RequestMapper()
{

}

void RequestMapper::service(HttpRequest &request, HttpResponse &response)
{
    QByteArray path=request.getPath();
    QByteArray method = request.getMethod();
    QByteArray nm = request.getParameter("nm");
    qDebug() << "RequestMapper: path=" << path.data();
    qDebug() << "RequestMapper: method=" << method.data();
     qDebug() << "RequestMapper: nm=" << nm.data();

    if ( path=="/hello") {
        m_helloController.service(request,response);
    }


}

第五步 自定义业务请求处理类

HelloController .h

#ifndef HELLOCONTROLLER_H
#define HELLOCONTROLLER_H

#include <QObject>
#include "httprequesthandler.h"
using namespace stefanfrings;
#include "json.hpp"
using namespace nlohmann;
#include <string>
using namespace std;
class HelloController : public QObject
{
    Q_OBJECT
public:
    explicit HelloController(QObject *parent = 0);
    void service(HttpRequest& request, HttpResponse& response);

signals:

public slots:
};

#endif // HELLOCONTROLLER_H

HelloController.cpp

#include "HelloController.h"

HelloController::HelloController(QObject *parent) : QObject(parent)
{

}

void HelloController::service(HttpRequest &request, HttpResponse &response)
{

   QByteArray body = request.getBody();
   qDebug() << body;

    json res;
    res["code"] = 200;
    res["mesage"] = "success";

    string str = res.dump(4);
    //    response.setStatus(404);
    response.write(str.c_str());
}

第六步 测试

服务运行示例

在这里插入图片描述

浏览器发请求示例

在这里插入图片描述

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值