在主线程中联网,不使用多线程

(不会卡主线程)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
QUrl url(ui->lineEdit->text());
QNetworkAccessManager manager;
QEventLoop loop;
QTextCodec* codec;
QNetworkReply* reply;

reply = manager.get(QNetworkRequest(url));
//请求结束并下载完成后,退出子事件循环
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
//开启子事件循环
loop.exec();

QString codeContent = reply->readAll();

//一定要注意编码问题,否则很容易出现乱码的
//codec = QTextCodec::codecForHtml(codeContent.toAscii());
//codeContent = codec->toUnicode(codeContent.toAscii());