1. Simple loading method:
void widget::on_pushButton_clicked(){
QString szUrl="https://XXX9a74.jpg";
Qurl url (szUrl);
QNetworkAccessManager manager;
QEventLoop loop;
// qDebug() << "Reading picture form " << url;
QNetworkReply *reply = manager.get(QNetworkRequest(url));
// request and the end of the download is complete, exit the sub-cycle events
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
// event loop opener
loop.exec();
QByteArray jpegData = reply->readAll();
QPixmap pixmap;
pixmap.loadFromData(jpegData);
ui-> label-> setPixmap (pixmap); // you display pictures in QLabel
}
2. Save the file to a local
void widget::downloadFileFromUrl(QString strUrl, QString strFilePath){
qDebug() << strUrl << " " << strFilePath;
QFile file;
file.setFileName(strFilePath);
if(file.open(QIODevice::WriteOnly))
{
QByteArray byte = InitGetRequest(strUrl, "downImgFromUrl");
file.write(byte);
file.close();
}
}
//get
QByteArray widget::InitGetRequest(QString url, QString obj)
{
//循环拼接
QString baseUrl =url;
//构造请求
QNetworkRequest request;
request.setUrl(QUrl(baseUrl));
QNetworkAccessManager *manager = new QNetworkAccessManager();
// 发送请求
QNetworkReply *pReplay = manager->get(request);
//开启一个局部的事件循环,等待响应结束,退出
QEventLoop eventLoop;
QObject::connect(pReplay,SIGNAL(finished()), &eventLoop, SLOT(quit()));
//add timeout deal
QTimer *tmpTimer = new QTimer();
connect(tmpTimer,SIGNAL(timeout()),&eventLoop, SLOT(quit()));
tmpTimer->setSingleShot(true);
tmpTimer->start(5000);
eventLoop.exec();
tmpTimer->stop();
if (pReplay->error() == QNetworkReply::NoError)
{
qInfo() << QString("request %1 NoError").arg(obj);
}
else
{
qWarning()<<QString("request %1 handle errors here").arg(obj);
QVariant statusCodeV = pReplay->attribute(QNetworkRequest::HttpStatusCodeAttribute);
//statusCodeV是HTTP服务器的相应码,reply->error()是Qt定义的错误码,可以参考QT的文档
qWarning()<<QString("request %1 found error ....code: %2 %3").arg(obj).arg(statusCodeV.toInt()).arg((int)pReplay->error());
qWarning(qPrintable(pReplay->errorString()));
}
//获取响应信息
QByteArray bytes = pReplay->readAll();
return bytes;
}