我們使用QNetworkAccessManager
來請求遠程URL,但是我們遇到了一個問題:即使它可以獲取響應主體大小,但它不能獲取任何html。QNetworkAccessManager無法獲得任何HTML
這是代碼:
manager=new QNetworkAccessManager(0);
cookie = new QNetworkCookieJar(0);
manager->setCookieJar(cookie);
QString str_url="http://www.wangdaizhijia.com/daohang.html";
QNetworkRequest request;
request.setUrl(QUrl(str_url));
request.setRawHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
request.setRawHeader("Accept-Language", "zh-CN,zh;q=0.8");
request.setRawHeader("Cache-Control", "no-cache");
request.setRawHeader("Connection", "keep-alive");
request.setRawHeader("DNT","1");
request.setRawHeader("Pragma","no-cache");
request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36");
QNetworkReply *reply=manager->get(request);
QEventLoop eventLoop;
QTimer timer;
QObject::connect(reply, SIGNAL(finished()),&eventLoop, SLOT(quit()));
QObject::connect(&timer, SIGNAL(timeout()),&eventLoop, SLOT(quit()));
timer.start(5*1000);
eventLoop.exec();
if(!timer.isActive())
{
timer.stop();
}
QByteArray temp=reply->readAll();
qDebug()<<"size is"<<temp.size();
qDebug()<<"html is"<<temp;
如果我們要求另一個網址,如http://www.google.com,它的工作。爲什麼?
看起來像你得到的答覆之前,定時器是越來越過期。但是正如@iziseo所建議的那樣,爲什麼你要創建Event Loop並且不使用默認的信號插槽? – Kunal 2015-04-02 10:12:55