我正按照an example in the QtWebkit documentation编写缩略图生成器。我想避免错误页面的屏幕截图,例如404 not found
或503 Internal server error
。
但是,即使页面发出HTTP错误,QWebPage::loadFinished()信号始终会以ok = true
发出。 QtWebkit中有没有办法检查响应的HTTP状态代码?
答案 0 :(得分:15)
事实证明,您需要监控与QWebPage关联的QNetworkAccessManager并等待finished(...)信号。然后,您可以通过询问QNetworkRequest::HttpStatusCodeAttribute
属性来检查HTTP响应并检查其状态代码。
在代码中更好地解释:
void MyClass::initWebPage()
{
myQWebPage = new QWebPage(this);
connect(
myQWebPage->networkAccessManager(), SIGNAL(finished(QNetworkReply *)),
this, SLOT(httpResponseFinished(QNetworkReply *))
);
}
void MyClass::httpResponseFinished(QNetworkReply * reply)
{
switch (reply->error())
{
case QNetworkReply::NoError:
// No error
return;
case QNetworkReply::ContentNotFoundError:
// 404 Not found
failedUrl = reply->request.url();
httpStatus = reply->attribute(
QNetworkRequest::HttpStatusCodeAttribute).toInt();
httpStatusMessage = reply->attribute(
QNetworkRequest::HttpReasonPhraseAttribute).toByteArray();
break;
}
}
还有更多NetworkErrors可供选择,例如对于TCP错误或HTTP 401。
答案 1 :(得分:2)
这就是我在移植项目中使用的内容。它会检查回复并决定是否开始提出请求。退出部分正在进行中,但我留下了评论。
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
Q_CHECK_PTR(reply);
QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
if (!statusCode.isNull() && statusCode.toInt() >= 400){
//INVALID_SERVER_RESPONSE_BACKOFF;
qDebug() << "server returned invalid response." << reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
return;
}else if (!statusCode.isNull() && statusCode.toInt() != 200){
//INVALID_SERVER_RESPONSE_NOBACKOFF;
qDebug() << "server returned invalid response." << reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
return;
}