1

我试图找出在 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;
        }
    }

然而,状态总是空的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;
    }

但这不叫。

我怎样才能知道出了什么问题?

4

1 回答 1

1

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

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

于 2020-06-12T13:39:02.273 回答