6

we are using QtWebKit 4.7 and want to know when a frame load does a redirect.

At the moment we are counting the outgoing requests within a subclass of the QNetworkAccessManager, where we do overwrite createRequest.

This works in most cases fine, but when the first response is 301 or 302 (redirect), it is swallowed somewhere.

We simply request a url the following way:

QNetworkRequest request(QUrl("http://www.twitter.com")); // 301 to twitter.com
frame->load(request);
Dag
  • 10,079
  • 8
  • 51
  • 74

2 Answers2

8

Handle the QNetworkReply yourself, get the status code from the reply and do a QWebFrame::setcontent.

QNetworkRequest request(QUrl("http://www.twitter.com")); // 301 to twitter.com
connect (frame->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*), this, SLOT(onFinished(QNetworkReply*));
frame->page()->networkAccessManager()->get(request);

[...]

void onFinished(QNetworkReply* reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        switch (statusCode) {
            case 301:
            case 302:
            case 307:
                qDebug() << "redirected: " << reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
                break;

            case 200:
                frame->setContent(reply->readAll());
                break;
        }
    }
}
Chris Browet
  • 4,156
  • 20
  • 17
  • We tried this as well, but none of the logged status codes showed a 30x :( .. for the moment we go with your [first solutions](http://stackoverflow.com/a/9516092/363281) plus some quirks. – Dag Mar 05 '12 at 09:15
  • That probably means that there are multiple redirections. What you could do is specify your own QNetworkAccessManager to the page with "QWebPage::setNetworkAccessManager" and "connect" this one, so that you can trap all network requests, even hidden ones. – Chris Browet Mar 05 '12 at 09:57
3

Use the void QWebFrame::urlChanged ( const QUrl & url ) signal to detect url changes, i.e. redirects, i.e.

QNetworkRequest request(QUrl("http://www.twitter.com")); // 301 to twitter.com
connect(frame, SIGNAL(urlChanged (const QUrl&)), this, SLOT(onRedirected(const QUrl&));
frame->load(request);
Chris Browet
  • 4,156
  • 20
  • 17
  • This approach has some issues (we already tried this). 1. We don't get the statuscode (which isn't that necessary, but it has to be a event that is one of 301/302) 2. When the url is changed in javascript, the event is also triggered 3. In our logs this signal came after httpResponseFinished, which is also confusing, since the network traffic we capture the redirect cames before some 20x codes – Dag Mar 01 '12 at 12:49