qt截获html请求

12 篇文章 0 订阅
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()->setForwardUnsupportedCon tent(true);



来自http://blog.sina.com.cn/s/blog_671732440100y3xx.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值