Sometimes it is necessary to alter the user-agent header for the request sent by QWebView. Some websites may refuse your visit if you do not use a normal browser. In such case we should fake a user-agent header as if the request comes from a normal browser. If you search google for how to change the user-agent in a QWebView, you will definitely find two solutions. One is as follows:
QNetworkRequest request;
request.setUrl(QUrl(url));
request.setRawHeader("User-Agent", "your customized user-agent");
load(request);
Unfortunately, it does not work. The default user agent is emitted when you load a url in a QWebView.
The second is subclassing QWebPage to overload the protected virtual function userAgentForUrl. This function is called with the url that is being loaded so you can return different user agent for different urls. But pay special attention when you overload this function, the correct form is:
QString userAgentForUrl(const QUrl &url ) const
{
return yournewuseragent;
}
Do not forget the const keyword besides the function name, otherwise you will not overload the function of QWebPage but create a new function in your subclass which will never be called.
Comments are closed, but trackbacks and pingbacks are open.