Qt QWebView class custom User-Agent

為{幸葍}努か 提交于 2019-12-28 13:51:12

问题


Is there an easy way to setup the User-Agent the QWebView class is using?

The only relevant link I found searching was this

http://www.qtforum.org/article/27073/how-to-set-user-agent-in-qwebview.html

I'm learning C++/Qt right now and I don't really understant what's explained on that website. Maybe someone knows an easy way to do it? Or can help me understand that code?


回答1:


Qt allows you to provide a user agent based on the URL rather than a single user agent no matter what the URL is. The idea then is to return the user agent any time a new webpage is created:

class UserAgentWebPage : public QWebPage {
    QString userAgentForUrl(const QUrl &url ) const {
        return QString("My User Agent");
    }
};

In order to use that page instead of the standard page that is created, you can set that page on the browser control object before making the request:

yourWebView->setPage(new UserAgentWebPage(parent));

I would actually expect a factory to be present somewhere that will guarantee that the webpage created is always of a certain type, but I didn't see one.

Yet another option should be to set the user agent header within the QNetworkRequest:

QNetworkRequest request = new QNetworkRequest();
request->setRawHeader(
    QString("User-Agent").toAscii(),
    QString("Your User Agent").toAscii()
    );
// ... set the URL, etc.
yourWebView->load(request);

You would actually want to check whether it's toAscii() or toUtf8() or one of the other variants as I'm not sure exactly what the HTTP standard allows.




回答2:


simply,

class myWebPage : public QWebPage
{
    virtual QString userAgentForUrl(const QUrl& url) const {
        return "your user agent";
    }
};

//Attention here is new myWebPage() not new myWebPage(parent) 
UI->webView->setPage(new myWebPage());


来源:https://stackoverflow.com/questions/3906964/qt-qwebview-class-custom-user-agent

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