QWebEngineView实现HTTP请求的拦截

在配置文件上实现QWebEngineUrlRequestInterceptor接口并安装拦截器,在它们到达 Chromium的网络堆栈之前,可以拦截。阻塞和修改URL请求。它是一个抽象类,意味着需要子类化它才能得到所需的内容。

#include <QWebEngineUrlRequestInterceptor>
#include <QDebug>

class RequestInterceptor : public QWebEngineUrlRequestInterceptor
{
public:
 explicit RequestInterceptor(QObject * parent = Q_NULLPTR) : QWebEngineUrlRequestInterceptor(parent) {}
 virtual void interceptRequest(QWebEngineUrlRequestInfo & info) Q_DECL_OVERRIDE;
};

void RequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo & info)
{
//Intercepting the requested URL
 QUrl url = info.requestUrl();
 qDebug() <<"Request URL:" <<url;
//Optionally redirect the request URL but it only works for requests 
//without payload data such as GET ones
 info.redirect(QUrl("https://www.google.com"));
//Set HTTP header
 QByteArray httpHeaderName ="SomeHeaderName";
 QByteArray httpHeaderValue ="SomeHeaderValue";
 info.setHttpHeader(httpHeaderName, httpHeaderValue);
}

然后,需要在中为特定的QWebEnginePage 指定指向该拦截器的指针,如下所示:

QWebEngineView * view = new QWebEngineView;
RequestInterceptor * interceptor = new RequestInterceptor(view);
QWebEngineProfile * profile = new QWebEngineProfile(view);
profile->setRequestInterceptor(interceptor);
QWebEnginePage * page = new QWebEnginePage(profile, view);
view->setPage(page);

 

原创文章,作者:365开发网,如若转载,请注明出处:https://www.365codes.com/248.html