QNetworkAccessManager HTTP Put request not working

353 Views Asked by At

After an exhaustive search on the web about this issue, none of the answers found solved it.

Using the technology Qt_5_15_2_MSVC2019_64/Microsoft Visual C++ Compiler, I'm trying to send a JSON file through HTTP put request from QNetworkAccessManager to a custom QTcpServer, but when doing so, only HTTP headers are received (even twice) but not the JSON file in itself.

Snippet Code:

void Sender::putParameters(const QString& p_parameters)  {
   QJsonDocument docJson = QJsonDocument::fromJson(p_parameters.toUtf8());
   QByteArray data = docJson.toJson();
   QUrl url= QUrl("http://127.0.0.1:80/api/devices/1285/parameters");
   QNetworkAccessManager* nam = new QNetworkAccessManager(this); // Even tried to put as member variable but still did not work

   QNetworkRequest networkReq(url);
   networkReq.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
   networkReq.setRawHeader("Content-Length", QByteArray::number(data.size()));
   
   QObject::connect(nam, &QNetworkAccessManager::finished, this, 
   &Sender::validateParameters);
   nam->put(networkReq, data);

   if(docJson.isEmpty())
      qDebug() << "JSON was empty";
}

Result QTcpServer: enter image description here

With Poco library there's no issue it works, or sending HTTP put request via Postman it does work.

2

There are 2 best solutions below

1
Julien Mayalu On

@dabbler

Sorry for the late answer but here is the code snippet of the Server : enter image description here

With postMan and Poco it's working perfectly, so I don't know if the issue is then related to the server, and for the client side @Dmitry you're right I should use QJsonDocument::isNull instead (but I used isEmpty() just for demonstration purpose that I wasn't sending an invalid Json which is not the case, the json is valid).

0
Julien Mayalu On

Yes my bad @Syfer So I have the class Server inheriting from QTcpServer and overriding function incomingConnection such as : void incomingConnection(qintptr) Q_DECL_OVERRIDE;

Here is the code snippet:

Server::Server(QObject* parent) : QTcpServer(parent) 
{
    if(listen(QHostAddress::Any, 80))
        qDebug() << "Ok listening port 80";
    else 
        qCritical() << "Fail listening";
}

void Server::incomingConnection(qintptr p_intPtrSocket)
{
    QTcpSocket* socketClient = new QTcpSocket(this);
    socketClient->setSocketDescriptor(p_intPtrSocket);
        
    connect(socketClient, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
}

void Server::onReadyRead()
{
    QTcpSocket* socketClient = (QTcpSocket*)sender();
    QString fullClientRequest = QString::fromUtf8(socketClient->readAll());
    QStringList clientReq = fullClientRequest.split("\n");
        
    qDebug() << "client response: " << clientReq;
 }