2

我正在使用下面的代码发出 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但仍然无法正常工作。

4

2 回答 2

2

即使没有发出请求,您也在分析状态,因此结果为 null 是有效的,您应该做的是在发出完成的信号时分析它:

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:

有没有办法在完成后返回该回复?

是的,使用 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();
}
于 2019-10-15T23:45:23.157 回答
0

您可以包含 QtNetworkReply 和 QEventLoop 类并使用信号/槽机制。

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();
于 2022-01-10T06:54:04.967 回答