1、简介
此示例演示一个简单的HTTP客户端如何从远程主机获取文件。
2、使用类
QUrl:url抽象类
QUrl::fromUserInput:从QString转换成QUrl
QNetworkAccessManager:网络访问API围绕一个QNetworkAccessManager对象构造,该对象保存其发送的请求的通用配置和设置。创建QNetworkAccessManager对象后,应用程序可以使用它通过网络发送请求。提供了一组标准函数,这些函数接受一个请求和可选数据,并且每个函数都返回一个QNetworkReply对象。返回的对象用于获取响应于相应请求而返回的任何数据。
QNetworkRequest:发送的请求
QNetworkReply:收到的回应
QNetworkAccessManager、QNetworkRequest、QNetworkReply一组简单的用法如下:
QNetworkRequest request;
request.setUrl(QUrl("http://qt-project.org"));
request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
QNetworkReply *reply = manager->get(request);
connect(reply, &QIODevice::readyRead, this, &MyClass::slotReadyRead);
connect(reply, &QNetworkReply::errorOccurred,
this, &MyClass::slotError);
connect(reply, &QNetworkReply::sslErrors,
this, &MyClass::slotSslErrors);
本例中主要用法如下,重点关注QNetworkReply的各种信号的使用,
如:QNetworkReply::finished、QIODevice::readyRead、QNetworkReply::downloadProgress、QNetworkReply::finished
// QNetworkAccessManager qnam;
QNetworkReply *reply = qnam.get(QNetworkRequest(url));
connect(reply, &QNetworkReply::finished, this, &HttpWindow::httpFinished);
connect(reply, &QIODevice::readyRead, this, &HttpWindow::httpReadyRead);
ProgressDialog *progressDialog = new ProgressDialog(url, this);
connect(reply, &QNetworkReply::downloadProgress, progressDialog, &ProgressDialog::networkReplyProgress);
connect(reply, &QNetworkReply::finished, progressDialog, &ProgressDialog::hide);
progressDialog->show();