QtWebkit加载html页面,html中会有很多的请求,比如<img id="testImg" src="http://*.jpg" width="200" height="200" title="test图片"/>等等,如果想截获这些请求,然后自定义应答...
1.定义一个类,继承QNetworkAccessManager(请求)
#ifndef NETWORKACCESSMANAGER_H
#define NETWORKACCESSMANAGER_H
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkProxy>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>
class NetworkAccessManager : public QNetworkAccessManager
{
Q_OBJECT
public:
explicit NetworkAccessManager(QNetworkAccessManager *manager, QObject *parent);
protected:
QNetworkReply * createRequest(QNetworkAccessManager::Operation operation,
const QNetworkRequest &request, QIODevice *device);
};
#endif // NETWORKACCESSMANAGER_H
#include "networkaccessmanager.h"
#include <QtCore/QDebug>
NetworkAccessManager::NetworkAccessManager(QNetworkAccessManager *manager, QObject *parent)
: QNetworkAccessManager(parent)
{
setCache(manager->cache());
setCookieJar(manager->cookieJar());
setProxy(manager->proxy());
setProxyFactory(manager->proxyFactory());
}
QNetworkReply * NetworkAccessManager::createRequest(QNetworkAccessManager::Operation operation,
const QNetworkRequest &request, QIODevice *device)
{
if (request.url().scheme() != "http")
return QNetworkAccessManager::createRequest(operation, request, device);
else
return new BlobReply(request.url);
}
2.定义一个类,继承QNetworkReply(应答)
#ifndef BLOBREPLY_H
#define BLOBREPLY_H
#include <QtNetwork/QNetworkReply>
class BlobReply : public QNetworkReply
{
Q_OBJECT
public:
BlobReply(const QUrl &url);
void abort();
protected:
qint64 readData(char *data, qint64 maxSize);
};
#endif // BLOBREPLY_H
#include "blobreply.h"
#include <QtCore/QDebug>
BlobReply::BlobReply(const QUrl &url)
: QNetworkReply()
{
qDebug() << url.toString();
}
void BlobReply::abort()
{
}
qint64 BlobReply::readData(char *data, qint64 maxSize)
{
return -1;
}
3.在初始化webview的时候,实例化上面的东东
QNetworkAccessManager *oldManager = ui->webView->page()->networkAccessManager();
NetworkAccessManager *newManager = new NetworkAccessManager(oldManager, this);
ui->webView->page()->setNetworkAccessManager(newManager);
ui->webView->page()->setForwardUnsupportedContent(true);
如有技术问题,请咨询博主QQ...
http://blog.sina.com.cn/s/blog_671732440100y3xx.html