我想下载1张图片并保存。以下是我到目前为止的情况:
QCoreApplication a(argc, argv);
QNetworkAccessManager *manager = new QNetworkAccessManager();
QNetworkReply *img = manager->get(QNetworkRequest(QUrl("http://placekitten.com/200/300")));
QImage* img2 = new QImage();
img2->save(img->readAll(), "omg2.png");
但是ID不起作用,请帮忙!
编辑: 那也不行,我在控制台得到“oops”:
QNetworkAccessManager *manager = new QNetworkAccessManager();
//connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
QNetworkReply *img = manager->get(QNetworkRequest(QUrl("http://placekitten.com/200/300")));
QImage* img2 = new QImage();
img2->loadFromData(img->readAll());
if(img2->isNull())
std::cout << "oops";
img2->save("omg2.png");
编辑:
在vtable
错误仍然存在后,qmake
出现奇怪的错误:
#include <QtCore/QCoreApplication>
#include <QNetworkAccessManager>
#include <QtNetwork>
#include <QImage>
#include <QPixmap>
#include <iostream>
class omg : public QObject{
Q_OBJECT
public:
void start(){
QNetworkAccessManager *manager = new QNetworkAccessManager();
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://placekitten.com/200/300")));
}
public slots:
void replyFinished(QNetworkReply* reply)
{
//Check for errors first
QImage* img2 = new QImage();
img2->loadFromData(reply->readAll());
if(img2->isNull())
std::cout << "oops";
img2->save("omg2.png");
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
omg *o = new omg();
o->start();
return a.exec();
}
答案 0 :(得分:5)
即使在发出Http请求之前,您也试图从QNetworkReply读取数据,更不用说完成了。
NetworkAccessManager *manager = new QNetworkAccessManager();
connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://placekitten.com/200/300")));
...
/*Define slot and read data from QNetworkreply*/
void finished(QNetworkReply* reply)
{
//Check for errors first
QImage* img2 = new QImage();
img2->loadFromData(reply->readAll());
if(img2->isNull())
std::cout << "oops";
img2->save("omg2.png");
}