/*
strUrl:下载图片时需要的url
strFilePath:下载图片的位置(/home/XXX/YYY.png)
*/
void ThorPromote::downloadFileFromUrl(QString strUrl, QString strFilePath)
{
qDebug() << strUrl << " " << strFilePath;
QFile file;
file.setFileName(strFilePath);
if(file.open(QIODevice::WriteOnly))
{
QByteArray byte = webhelper::InitGetRequest(strUrl, "downImgFromUrl");
file.write(byte);
file.close();
}
} //get
QByteArray webhelper::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();
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;
}