QtWebkit:如何检查HTTP状态代码? [英] QtWebkit: How to check HTTP status code?

查看:151
本文介绍了QtWebkit:如何检查HTTP状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照编写缩略图生成器QtWebkit文档中的示例.我想避免错误页面如404 not found503 Internal server error的屏幕截图.

I'm writing a thumbnail generator as per an example in the QtWebkit documentation. I would like to avoid screenshots of error pages such as 404 not found or 503 Internal server error.

但是, QWebPage :: loadFinished()信号始终与ok = true一起发出即使页面显示HTTP错误. QtWebkit中是否可以检查响应中的HTTP状态代码?

However, the QWebPage::loadFinished() signal is always emitted with ok = true even when the page gives an HTTP error. Is there a way in QtWebkit to check the HTTP status code on a response?

推荐答案

原来,您需要监视 QNetworkAccessManager ,并等待完成(...)信号.然后,您可以通过询问QNetworkRequest::HttpStatusCodeAttribute属性来检查HTTP响应并检查其状态代码.

Turns out you need to monitor the QNetworkAccessManager associated with your QWebPage and wait for a finished(...) signal. You can then inspect the HTTP response and check its status code by asking for the QNetworkRequest::HttpStatusCodeAttribute attribute.

最好在代码中进行解释:

It's better explained in code:

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

还有更多网络错误可供选择,例如TCP错误或HTTP 401.

There are more NetworkErrors to choose from, e.g. for TCP errors or HTTP 401.

这篇关于QtWebkit:如何检查HTTP状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆