gpt4 book ai didi

qt - 使用 QWebEngineView 捕获服务器响应

转载 作者:行者123 更新时间:2023-12-03 16:05:48 28 4
gpt4 key购买 nike

我正在尝试在 Qt 中创建一个加载 URL 的对话框(我不想向最终用户公开,因此是一个对话框)。一旦用户在页面上输入了他们的凭据,服务器就会返回一个我想要捕获的重定向 URL。我怎样才能做到这一点?

QtWebkit 使这很容易做到,因为 QWebView 有一个 QNetworkAccessManager 对象。但是对于 QtWebEngine,QWebEngineView 类没有这个能力。前者还允许通过使用 QNetworkRequest 类为任何请求设置 HTTP header ,然后在 QWebView 中使用这些特定请求加载请求。我如何用 QWebEngineView 做到这一点?

最佳答案

从 Qt 5.6 开始,您尝试使用 QWebEngineView 实现的建议解决方案是 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.



它是一个抽象类,这意味着您需要对其进行子类化以获得您想要的:
#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);
}

然后你需要在 QWebEngineProfile中注册这个拦截器的指针对于特定的 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);

关于qt - 使用 QWebEngineView 捕获服务器响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40309105/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com