NetworkReply HttpStatusCode QVariant(无效)

NetworkReply HttpStatusCode QVariant(Invalid)

我正在使用下面的代码发出 http 请求:

QNetworkReply* ApiRequest::req(QString url, QString method, QByteArray data) {
    QByteArray request_method = method.toUtf8();
    QNetworkAccessManager* manager = new QNetworkAccessManager();
    QNetworkRequest request("http://127.0.0.1:9090" + url);
    request.setRawHeader("Content-Type", "application/json");
    QNetworkReply* reply = manager->sendCustomRequest(request, request_method, data);
    return reply;
}

void ApiRequest::requestConfig()
{
    NetworkReply* reply = req("/configs",
        "GET",
        "");
}

远程服务器确实执行了请求并回复了 204 代码。
我已经使用 wireshark 来捕获并确保它回复了 204 No Content.
但是,那里的输出是QVariant(Invalid)toInt的输出是0
我尝试将 PUT 更改为 GET 但它仍然不起作用。

即使没有发出请求,你也在分析状态,所以结果为空是有效的,你应该做的是在发出完成信号时分析它:

QNetworkReply* reply = mg->sendCustomRequest(request, "PUT", "....some json....");
connec(reply, &QNetworkReply::finished, [reply](){
    qDebug() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
});

更新:

connec(mg, &QNetworkAccessManager::finished, [](QNetworkReply *reply){
    qDebug() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
});

更新 2:

有没有办法return完成后回复?

是的,使用 QEventLoop,但总的来说这是一个糟糕的设计,因为您应该使用信号和槽来通知您更改。

QNetworkReply* ApiRequest::req(const QString & url, const QString & method, const QByteArray & data) {
    QByteArray request_method = method.toUtf8();
    QNetworkAccessManager manager;
    QNetworkRequest request("http://127.0.0.1:9090" + url);
    request.setRawHeader("Content-Type", "application/json");
    QNetworkReply* reply = manager.sendCustomRequest(request, request_method, data);
    QEventLoop loop;
    connec(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();
    return reply;
}

// ...

void ApiRequest::requestConfig()
{
    QNetworkReply* reply = req("/configs", "GET", "");
    // ...
    reply->deleteLater();
}

您可以包含 QtNetworkReply 和 QEventLoop 类 并使用 signal/slot 机制。

QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QUrl resource(url);
QNetworkRequest request(resource);
QNetworkReply *reply = manager->get(request);
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QJsonObject jsonObject = QJsonDocument::fromJson(reply->readAll()).object();