Михаиллл
МихаилллFeb. 18, 2020, 10:18 a.m.

Как в QtWebApp принять POST запрос

QtWebApp, POSt

Добрый день.
Разбираюсь в библиотеке QtWebApp.
Так обрабатываю get запрос. Подскажите пожалуйста, как принять и обработать POST запрос?
И может быть Вы знаете, почему qDebug() ничего не выводит?

void RequestHandler::service(HttpRequest& request, HttpResponse& response)
{
    QByteArray path=request.getPath();   
    //response.setHeader("Content-Type", "text/html; charset=ISO-8859-1");
    response.setHeader("Content-Type", "application/json; charset=ISO-8859-1");

    //обработчик запросов
    if (path.startsWith("/111"))
    {
        response.write("1 - 1 - 1",true);
        qDebug()<<11111;
    }
    else if (path.startsWith("/222"))
    {
        response.write("2 - 2 - 2",true);
    }
    else if (path.endsWith("/333"))
    {
        response.write("3 - 3 - 3",true);
    }
    else
    {
        response.write("0 - 0 - 0",true);
    }

    qDebug("Conroller: finished request");

    // Clear the log buffer
    if (logger)
    {
       logger->clear();
    }
}
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

12
Ruslan Polupan
  • Feb. 18, 2020, 10:35 a.m.

Я читаю параметры запроса. если они не пустые сохраняю в сессию. затем ими пользуюсь

вот мой requestmapper.cpp

#include "requestmapper.h"
#include "global.h"


RequestMapper::RequestMapper(QObject *parent) :
    HttpRequestHandler(parent)
{
    userID = 0;
    modelUsers = new QSqlQueryModel(this);
    modelUsers->setQuery("SELECT c.user_id, c.username, c.userpass FROM clientusers c where c.isactive = 'true'");
}


void RequestMapper::service(HttpRequest &request, HttpResponse &response)
{
    HttpSession session=sessionStore->getSession(request,response,true);

    QByteArray username=request.getParameter("username");
    QByteArray password=request.getParameter("password");
    QByteArray objectID=request.getParameter("objectID");
    QByteArray shiftID =request.getParameter("shiftID");

    qDebug("username=%s",username.constData());
    qDebug("password=%s",password.constData());
    qDebug("objectID=%s",objectID.constData());
    qDebug("shiftID=%s",shiftID.constData());

    if(username.length() !=0){
        userID=getUserID(QString(username), QString(password));
    }

    QByteArray path=request.getPath();
    qDebug("RequestMapper: path=%s",path.data());

    if(path == "/"){
        response.redirect("/login.html");
        return;
    } else if (path=="/login.html") {
        staticFileController->service(request,response);
    } else if (path == "/objects" && userID > 0){
        session.set("userID",userID);
        objectsList.service(request,response);
    } else if(path == "/shifts" && objectID.length()>0) {
        session.set("objectID",objectID);
        shiftList.service(request,response);
    } else if (path == "/report" && shiftID.length()>0){
        session.set("shiftID",shiftID);
        shiftReport.service(request,response);
    }
    else {
        response.setStatus(404,"Not found");
        response.write("The URL is wrong, no such document.",true);
    }

    qDebug("RequestMapper: finished request");
}

uint RequestMapper::getUserID(QString login, QString pass)
{
    uint userID = 0;
    const int rowCount = modelUsers->rowCount();
    for(int row=0; row<rowCount; ++row){
        if(modelUsers->data(modelUsers->index(row,1)).toString() == login){
            if(modelUsers->data(modelUsers->index(row,2)).toString() == pass){
                userID = modelUsers->data(modelUsers->index(row,0)).toUInt();
                break;
            }
        }
    }
    return userID;

}

Если поможет ссылка на GitHub https://github.com/rust3128/MposOnlineReports

    Михаиллл
    • Feb. 18, 2020, 10:46 a.m.

    А у Вас qDebug() нормально выводит?

      Ruslan Polupan
      • Feb. 18, 2020, 10:52 a.m.

      да

      18.02.2020 16:57:57.940 0 DEBUG     HttpSession: (constructor) copy session {3540ed62-cd8b-4e00-8ca6-6ac5633dd22c} refCount=2
      18.02.2020 16:57:57.940 0 DEBUG     HttpSession: (constructor) copy session {3540ed62-cd8b-4e00-8ca6-6ac5633dd22c} refCount=3
      18.02.2020 16:57:57.940 0 DEBUG     HttpSession: (destructor) session {3540ed62-cd8b-4e00-8ca6-6ac5633dd22c} refCount=2
      18.02.2020 16:57:57.940 0 DEBUG     username=
      18.02.2020 16:57:57.940 0 DEBUG     password=
      18.02.2020 16:57:57.940 0 DEBUG     objectID=
      18.02.2020 16:57:57.940 0 DEBUG     shiftID=2020
      18.02.2020 16:57:57.940 0 DEBUG     RequestMapper: path=/report
      18.02.2020 16:57:57.940 0 DEBUG     HttpSession: (constructor) copy session {3540ed62-cd8b-4e00-8ca6-6ac5633dd22c} refCount=3
      18.02.2020 16:57:57.940 0 DEBUG     HttpSession: (constructor) copy session {3540ed62-cd8b-4e00-8ca6-6ac5633dd22c} refCount=4
      18.02.2020 16:57:57.940 0 DEBUG     HttpSession: (destructor) session {3540ed62-cd8b-4e00-8ca6-6ac5633dd22c} refCount=3
      18.02.2020 16:57:57.940 0 DEBUG     object ID report 1 shiftID report 2020
      18.02.2020 16:58:02.920 0 DEBUG     HttpConnectionHandler (0x114f200): disconnected
      18.02.2020 16:58:10.771 0 DEBUG     language=ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
      18.02.2020 16:58:10.771 0 DEBUG     TemplateCache: trying cached shiftreport
      18.02.2020 16:58:10.771 0 DEBUG     TemplateCache: trying file /home/rust/develop/MposOnlineReports/docroot/shiftreport.html
      18.02.2020 16:58:10.802 0 DEBUG     HttpSession: (destructor) session {3540ed62-cd8b-4e00-8ca6-6ac5633dd22c} refCount=2
      18.02.2020 16:58:10.802 0 DEBUG     RequestMapper: finished request
      18.02.2020 16:58:10.802 0 DEBUG     HttpSession: (destructor) session {3540ed62-cd8b-4e00-8ca6-6ac5633dd22c} refCount=1
      18.02.2020 16:58:10.802 0 DEBUG     HttpConnectionHandler (0x115e120): finished request
      18.02.2020 16:58:17.914 0 DEBUG     HttpSession: (constructor) copy session {3540ed62-cd8b-4e00-8ca6-6ac5633dd22c} refCount=2
      18.02.2020 16:58:17.915 0 DEBUG     HttpSession: (destructor) session {3540ed62-cd8b-4e00-8ca6-6ac5633dd22c} refCount=1
      
      
        Михаиллл
        • Feb. 18, 2020, 11:01 a.m.

        Странно, у меня дебаг не работает. Может быть Вы знаете причину?
        Отправляю такой запрос:

            QByteArray data = ("\n{\n\"UserId\" :\"");
            data.append("dgvwd");
            data.append("\",\n\"Message\" : \"");
            data.append("edgvedbed");
            data.append("\",\n\"Slag\" :\"");
            data.append("slag");
            data.append("\",\n\"Phone\" :\"");
            data.append("dbvgwdb");
            data.append("\"\n}\n\n");
            request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
            request.setHeader(QNetworkRequest::ContentLengthHeader,QByteArray::number(data.size()));
            myApiQuery.post(request, data);
        

        Принимаю его так:

        void RequestHandler::service(HttpRequest& request, HttpResponse& response)
        {
            QTextStream out(stdout);
        
        
            QByteArray username=request.getParameter("UserId");
            QByteArray password=request.getParameter("Message");
            QByteArray objectID=request.getParameter("Slag");
            QByteArray shiftID =request.getParameter("Phone");
        
            qDebug("UserId=%s",username.constData());
            qDebug("Message=%s",password.constData());
            qDebug("Slag=%s",objectID.constData());
            qDebug("Phone=%s",shiftID.constData());
            out << "UserId : "<<username.constData()<<"\n";
            out << "Message : "<<password.constData()<<"\n";
            out << "Slag : "<<objectID.constData()<<"\n";
            out << "Phone : "<<shiftID.constData()<<"\n";
        

        На выводе поля получаются пустые. Как вы думаете, почему это не работает?

          Ruslan Polupan
          • Feb. 18, 2020, 2:14 p.m.

          [logging]
          minLevel=0 такое значение?

            Михаиллл
            • Feb. 18, 2020, 3:16 p.m.

            Нет, стоит minLevel=1
            А что это значит?
            Поменял на 0, но ничего не изменилось.
            Файл настроек выглядит так

            [listener]
            ; host=192.168.0.100
            port=8080
            minThreads=4
            maxThreads=100
            cleanupInterval=60000
            readTimeout=60000
            maxRequestSize=16000
            maxMultiPartSize=10000000
            
            [logging]
            fileName=../logs/HttpSerwerQtWebApp.log
            minLevel=0
            bufferSize=100
            maxSize=1000000
            maxBackups=2
            timestampFormat=dd.MM.yyyy hh:mm:ss.zzz
            msgFormat={timestamp} {typeNr} {type} {thread} {msg}
            ; QT5 supports: msgFormat={timestamp} {typeNr} {type} {thread} {msg}\n  in {file} line {line} function {function}
            
            [docroot]
            path=docroot
            encoding=UTF-8
            maxAge=60000
            cacheTime=60000
            cacheSize=1000000
            maxCachedFileSize=65536
            
              Михаиллл
              • Feb. 19, 2020, 6:07 a.m.
              • The answer was marked as a solution.

              Вот так получается джисон из пост запроса , но дебаг к сожалению не заработал

              request.getBody()
              
                Ruslan Polupan
                • Feb. 19, 2020, 6:23 a.m.

                файл logger.cpp
                У вас так?

                        // If the type of the message is high enough, print the whole buffer
                        // With one Exception: INFO messages are treated like DEBUG messages here
                        QtMsgType level=(type==QtInfoMsg?QtDebugMsg:type);
                        if (level>=minLevel)
                
                  Михаиллл
                  • Feb. 19, 2020, 6:27 a.m.

                  У меня так же

                          // If the type of the message is high enough, print the whole buffer
                          // With one Exception: INFO messages are treated like DEBUG messages here
                          QtMsgType level=(type==QtInfoMsg?QtDebugMsg:type);
                          if (level>=minLevel)
                  

                  В лог дебаг записывает, но привычной записи в консоль qt не происходит

                    Ruslan Polupan
                    • Feb. 19, 2020, 6:46 a.m.

                    а туда и нету вывода

                      Михаиллл
                      • Feb. 19, 2020, 6:54 a.m.

                      понятно, думал что дебаг будет стандартно работать.
                      спасибо за помощь!

                        D
                        • Sept. 7, 2020, 11:40 a.m.

                        в main.cpp закомментил //logger->installMsgHandler();

                          Comments

                          Only authorized users can post comments.
                          Please, Log in or Sign up
                          AD

                          C ++ - Test 004. Pointers, Arrays and Loops

                          • Result:50points,
                          • Rating points-4
                          m

                          C ++ - Test 004. Pointers, Arrays and Loops

                          • Result:80points,
                          • Rating points4
                          m

                          C ++ - Test 004. Pointers, Arrays and Loops

                          • Result:20points,
                          • Rating points-10
                          Last comments
                          i
                          innorwallNov. 11, 2024, 10:12 p.m.
                          Django - Tutorial 055. How to write auto populate field functionality Freckles because of several brand names retin a, atralin buy generic priligy
                          i
                          innorwallNov. 11, 2024, 6:23 p.m.
                          QML - Tutorial 035. Using enumerations in QML without C ++ priligy cvs 24 Together with antibiotics such as amphotericin B 10, griseofulvin 11 and streptomycin 12, chloramphenicol 9 is in the World Health Organisation s List of Essential Medici…
                          i
                          innorwallNov. 11, 2024, 3:50 p.m.
                          Qt/C++ - Lesson 052. Customization Qt Audio player in the style of AIMP It decreases stress, supports hormone balance, and regulates and increases blood flow to the reproductive organs buy priligy online safe Promising data were reported in a PDX model re…
                          i
                          innorwallNov. 11, 2024, 2:19 p.m.
                          Heap sorting algorithm The role of raloxifene in preventing breast cancer priligy precio
                          i
                          innorwallNov. 11, 2024, 1:55 p.m.
                          PyQt5 - Lesson 006. Work with QTableWidget buy priligy 60 mg 53 have been reported by Javanovic Santa et al
                          Now discuss on the forum
                          i
                          innorwallNov. 11, 2024, 8:56 p.m.
                          добавить qlineseries в функции buy priligy senior brother Chu He, whom he had known for many years
                          i
                          innorwallNov. 11, 2024, 10:55 a.m.
                          Всё ещё разбираюсь с кешем. priligy walgreens levitra dulcolax carbs The third ring was found to be made up of ultra relativistic electrons, which are also present in both the outer and inner rings
                          9
                          9AnonimOct. 25, 2024, 9:10 a.m.
                          Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

                          Follow us in social networks