qnetworkreply 没有状态代码或错误但失败

qnetworkreply no statuscode or error but failing

我试图找出在 qt 中执行获取请求时出了什么问题。 我的 networkmanager 有以下插槽:

connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(requestFinished(QNetworkReply*)));

    connect(mgr, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(slotError(QNetworkReply::NetworkError)));

请求完成如下:

    void FirebaseInteractor::requestFinished(QNetworkReply *rep)
    {
        QVariant statusCode = rep->attribute( QNetworkRequest::HttpStatusCodeAttribute );
        int status = statusCode.toInt();
        if ( status != 200 )
        {
            QString reason = rep->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
            qDebug() << "Pushnotification Request failed : " <<reason;
        }
        else{
            qDebug() << "Pushnotification has been send: ";
        }
        if ( !statusCode.isValid() )
        {

            QString status = statusCode.toString(); // or status_code.toInt();
            qDebug() << "Failing " << status;
            int code = statusCode.toInt();
            qDebug() << "Pushnotification Request failed invalid status code." << QString::number(code);
            QString reason = rep->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
            qDebug() << "reason " << reason;
            return;
        }
    }

但是 Status 始终为空 Failing 并打印了 reason 但其后没有任何值(我期待一个原因,例如超时、401 等)。

我也试过:

    int status = statusCode.toInt();

    if ( status != 200 )
    {
        QString reason = rep->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
        qDebug() << "Pushnotification Request failed : " <<reason;
    }
    else{
        qDebug() << "Pushnotification has been send: ";
    }

But all reasons/codes are empty.

I also added:

    void FirebaseInteractor::slotError(QNetworkReply::NetworkError error)
    {
        qDebug() << "slotError" << error;
    }

但是这个不叫。

我怎样才能找出问题所在?

您可以直接使用以下方法获取错误:

qDebug() << reply->error();

如果网络请求从未发生,这将不起作用:

    if ( !statusCode.isValid() ) 

因为这意味着 QVariant 本身无效并且类型为 QMetaType::UnknownType Documentation。因此,它不会提供任何有关 http 请求中出错的信息。要解决这个问题,这里有一个简单的例子:

if (statusCode.isValid()) { // it needs to be valid
    qDebug() << "Status Code: " << statusCode.toString();
}

或者,您可以打开 QNetworkReply::Error()

void FirebaseInteractor::requestFinished(QNetworkReply *rep)
{
    switch (rep->error())
    {
       case QNetworkReply::NoError:
       // No error
       return;
       case QNetworkReply::TimeoutError:
       {
           auto httpStatus =
               reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
           auto httpStatusMessage = reply->attribute(
        QNetworkRequest::HttpReasonPhraseAttribute).toByteArray();
        //...
        break;
       }
    }
}