码迷,mamicode.com
首页 > 数据库 > 详细

qt截获html请求(继承QNetworkAccessManager和QNetworkReply)

时间:2017-01-27 07:14:51      阅读:779      评论:0      收藏:0      [点我收藏+]

标签:test   sch   com   blob   debug   factory   实例   end   tco   

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

qt截获html请求(继承QNetworkAccessManager和QNetworkReply)

标签:test   sch   com   blob   debug   factory   实例   end   tco   

原文地址:http://www.cnblogs.com/findumars/p/6352718.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!