尝试 POST 时连接已关闭

Connection closed while trying to POST

我是 QT 的新手,我正在尝试为我的应用程序建立 REST 服务(GET 和 POST)。同时 GET 需求工作正常,我无法执行 POST 需求(结果我从服务器回复中得到:连接关闭错误)。您有什么建议吗?

构造函数:

{
    net_acc_manager = new QNetworkAccessManager(this);
    connect(net_acc_manager, &QNetworkAccessManager::finished,this, &MyApp::httpFinished);
}

POST,我得到的响应:失败,错误代码 #2。服务器错误解释:连接关闭

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,那部分工作正常,输出:Http post 成功完成。

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 函数

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();
}

总算找到问题和解决办法了。看来问题出在按 POST 需求发布字符串。

来自 POST 函数的行:

QByteArray postdata="0000";

实际上应该是:

QByteArray postdata("\"0000\"");

谢谢。