QtWebkit: How to check HTTP status code?

2019-01-18 12:23发布

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.

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?

2条回答
Juvenile、少年°
2楼-- · 2019-01-18 12:59

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

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

查看更多
够拽才男人
3楼-- · 2019-01-18 12:59

This is what I'm using in a porting project. It checks the reply and decides to start backing off making request or not. The backing off part is in progress but I left the comments in.

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;
}
查看更多
登录 后发表回答