我正在根据an example in the QtWebkit documentation编写一个缩略图生成器。我想避免错误页面的屏幕截图,比如404 not found
或503 Internal server error
。
但是,即使页面出现QWebPage::loadFinished()错误,ok = true
也始终会发出HTTP信号。在QtWebkit中有没有办法检查响应上的状态码?
发布于 2010-12-02 09:01:27
事实证明,您需要监视与QWebPage关联的QNetworkAccessManager,并等待finished(...)信号。然后,您可以检查HTTP响应并通过请求QNetworkRequest::HttpStatusCodeAttribute
属性来检查其状态代码。
最好用代码来解释:
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 error或HTTP401。
发布于 2012-12-10 23:17:04
这是我在一个移植项目中使用的。它检查应答并决定是否开始后退请求。后退部分正在进行中,但我留下了评论。
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;
}
https://stackoverflow.com/questions/4330274
复制相似问题