我试图找出在qt中执行get请求时出了什么问题。 我的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;
}
但这不叫。
我怎样才能找出出了什么问题?
您可以使用以下方法直接获取错误:
qDebug() << reply->error();
如果网络请求从未发生过,这将不起作用:
if ( !statusCode.isValid() )
因为这意味着QVariant
本身无效,并且具有QMetaType::UnknownType
文档类型。因此,它不会提供有关 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;
}
}
}
你可以做:
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QByteArray data;
QUrl urlObject(url);
auto reply = manager->post(req,data);
QEventLoop eventLoop;
connect(reply, &QNetworkReply::finished,&eventLoop,&QEventLoop::quit);
eventLoop.exec();
qDebug()<<"reply->error()::::::::"<<reply->error();