I am new at QT and I am trying to establish REST service (GET and POST) for my application. Meanwhile GET demand works fine, I can not execute POST demand (as result I got from server reply: Connection closed error). Do you have any suggestions what is wrong?
Constructor:
{
net_acc_manager = new QNetworkAccessManager(this);
connect(net_acc_manager, &QNetworkAccessManager::finished,this, &MyApp::httpFinished);
}
POST, response I get: Failed, error code #2. Server error explanation: Connection closed
void MyApp::Post_demand()
{
QUrl url = QUrl("http://192.168.2.1/od/6040/00");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QByteArray postdata="0000";
net_acc_manager->post(request,postdata);
qCDebug(log_hal) << Q_FUNC_INFO << "Request POST posted" << full_url.toString();
}
GET, that part works fine, output: Http post finished successfully.
void MyApp::Get_demand()
{
QUrl url = QUrl("http://192.168.2.1/od/6040/00");
reply=net_acc_manager->get(QNetworkRequest(QUrl("http://192.168.2.1/od/6040/00")));
qCDebug(log_hal) << Q_FUNC_INFO << "Request GET posted" << full_url.toString();
}
HttpFinished function
void MyApp::httpFinished(QNetworkReply *n_reply)
{
qCDebug(log_hal) << Q_FUNC_INFO << "Http request finished. Status code:" << n_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (n_reply->error()) {
qCCritical(log_hal) << Q_FUNC_INFO << "Status code:" << n_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
qCCritical(log_hal) << Q_FUNC_INFO <<
QString("Failed, error code: #%1; Server error explanation: %2")
.arg(QString::number(n_reply->error())
, n_reply->errorString().replace(QRegExp("\%20"), " ")).toLatin1().data();
n_reply->deleteLater();
n_reply = Q_NULLPTR;
emit failed();
return;
}
qCDebug(log_hal) << QString("Http post finished successfully. Reply Text: %1\nElapsed time: %2 ms")
.arg(QString(n_reply->readAll()), QString::number(timer->elapsed())).toLatin1().data();
//dummy read, to clear buffer
n_reply->readAll();
n_reply->deleteLater();
n_reply = Q_NULLPTR;
emit finished();
}
after all, I have found the problem and solution. It appeared that the problem was at posting string at POST demand.
The line from POST function:
QByteArray postdata="0000";
Should actually be:
QByteArray postdata("\"0000\"");
Thanks anyway.