Search code examples
qthttp-postqnetworkaccessmanager

QNetworkAccessManager is not sending data part of POST request


When sending POST data to server, from Qt application looks everything good but data part of HTTP part were not sent. In Wireshark in POST packet is visible correct "Content-Length" value but size of whole HTTP segment is only about 226 bytes (is independent on POST data size).

I can't find reason why data part is not send. Any idea?

The application is running in console. A complete source is below.

project.pro:

QT += widgets
QT -= gui
QT += network

CONFIG += c++11

TARGET = POSTrequest
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

main.cpp:

#include <QObject>
#include <QApplication>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QNetworkRequest request(QUrl("http://www.server.com/index.php"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    QNetworkAccessManager manager;
    QNetworkReply *reply = manager.post(request, "a=aaaaaa");

    QObject::connect(reply, SIGNAL(finished()), &a, SLOT(quit()));

    return a.exec();
}

Solution

  • This works for me on both OS X and Windows:

    #post-request-36549732.pro
    QT = core network
    CONFIG += console c++11
    CONFIG -= app_bundle
    TARGET = post-request-36549732
    TEMPLATE = app
    SOURCES += main.cpp
    
    // main.cpp
    #include <QtNetwork>
    
    int main(int argc, char ** argv)
    {
        QCoreApplication a{argc, argv};
        QNetworkAccessManager manager;
        QByteArray post{"a="};
        post.append(QByteArray{512, 'b'});
        QNetworkRequest req(QUrl("http://server/test.php"));
        req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    
        // Must be a queued connection, or else the multi-threaded manager might
        // win the race and signal quit before `a.exec()` starts running. In such
        // case, the `quit()` is a NOP. We don't want that.
        QObject::connect(&manager, &QNetworkAccessManager::finished, &a, [](QNetworkReply * reply){
           qDebug() << reply->errorString();
           qApp->quit();
        }, Qt::QueuedConnection);
    
        manager.post(req, post);
        return a.exec();
    }
    

    You might be interpreting your Wireshark data incorrectly. Make sure you're looking at the Reassembled TCP aspect of the HTTP request. Here's how it looks for me; server is 192.168.2.1:

    wireshark capture screenshow