Capture server response with QWebEngineView

十年热恋 提交于 2019-12-17 19:56:02

问题


I'm trying to create a Dialog in Qt which loads a URL (which I do not want to expose to the end-user, hence a Dialog). Once the user has entered their credentials on the page, the server returns a redirect URL which I want to capture. How can I do this?

QtWebkit made this easy to do as QWebView had a QNetworkAccessManager object. But with QtWebEngine, the QWebEngineView class does not have this capability. The former also allowed HTTP headers to be set for any requests by using the QNetworkRequest class and then load requests with these specific requests in QWebView. How do I do this with QWebEngineView?


回答1:


Since Qt 5.6 the proposed solution for what you are trying to achieve with QWebEngineView is QWebEngineUrlRequestInterceptor:

Implementing the QWebEngineUrlRequestInterceptor interface and installing the interceptor on the profile enables intercepting, blocking, and modifying URL requests before they reach the networking stack of Chromium.

It is an abstract class which means you need to subclass it to get what you want:

#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);
}

Then you need to register the pointer to this interceptor in QWebEngineProfile for a particular QWebEnginePage, like this:

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);


来源:https://stackoverflow.com/questions/40309105/capture-server-response-with-qwebengineview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!