Pregunta

I use Qt, I found QWebView and QNetworkRequest can't share the cookies in my program.

I know I should set the cookiejar to QNetworkAccessManager and share it, so:

networkAccessManager = new QNetworkAccessManager();
networkAccessManager->setCookieJar(new CCookieJar);

QWebView* webView = new QWebView(this);
webView->page()->setNetworkAccessManager(networkAccessManager);

When I use webView to load a website and I login it. It ok. But while I set a timer to use QNetworkRequest to download the html, the webView will logout in the website, I look like the cookies have been reset, so the sessionid change.

QString surl = "http://www.website.com"
QNetworkRequest request;
request.setUrl(QUrl(surl));
QList<QNetworkCookie> cookies = networkAccessManager->cookieJar()->cookiesForUrl(surl);
for(QList<QNetworkCookie>::iterator it = cookies.begin(); it!=cookies.end(); it++)
{
    request.setHeader(QNetworkRequest::CookieHeader, QVariant::fromValue<QNetworkCookie>(*it));
}
QNetWorkReply* reply = networkAccessManager->get(request)
connect(reply, SIGNAL(finished()), this, SLOT(httpFinished()));

In the httpFinished I set the cookies to the networkAccessManager.

QNetworkReply* reply = qobject_cast<QNetworkReply *>(sender());
QVariant varCookies = reply->header(QNetworkRequest::SetCookieHeader);
QList<QNetworkCookie> cookies = varCookies.value< QList<QNetworkCookie> >();
networkAccessManager->cookieJar()->setCookiesFromUrl(cookies, reply->url());
reply->deleteLater();

I want the webView and the QNetworkRequest get the result can share the session so I can get the data at the login status. But my program doesn't work. I write the program code by search same example.

Can't you tell me what'wrong in my program, and how to correct it. Thanks!

¿Fue útil?

Solución

After I try, I found all I should do is add the webView's User-Agent header to the request.

For example:

request.setRawHeader("User-Agent", "mozilla/5.0 (windows NT 5.1) applewebki...");

Or rewrite the QWebPage's function userAgentForUrl(const QUrl& url), to return the agent you use in request.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top