一个网站内容下载的类和实现
高手请直接看最后几行
httpget.h---------------------------------
#ifndef HTTPGET_H
#define HTTPGET_H
#include <QObject>
class QUrl;
class QHttp;
class QFile;
class HttpGet : public QObject {
Q_OBJECT
public:
HttpGet(QObject *parent = 0);
void downloadFile(const QUrl &url);
signals:
void finished();
private slots:
void done(bool error);
private:
QHttp *http;
QFile *file;
};
#endif
httpget.cpp------------------------------------
#include <QtNetwork>
#include <QFile>
#include <iostream>
#include "HttpGet.h"
using namespace std;
HttpGet::HttpGet(QObject *parent) : QObject(parent) {
http = new QHttp(this);
connect(http, SIGNAL(done(bool)), this, SLOT(done(bool)));
}
void HttpGet::downloadFile(const QUrl &url) {
QFileInfo fileInfo(url.path());
QString fileName = fileInfo.fileName();
if (fileName.isEmpty()) {
fileName = "index.html";
}
file = new QFile(fileName);
if (!file->open(QIODevice::WriteOnly)) {
cerr << "Unable to save the file" << endl;
delete file;
file = 0;
return;
}
http->setHost(url.host(), url.port(80));
http->get(url.path(), file);
http->close();
}
void HttpGet::done(bool error) {
if (error) {
cerr << "Error: " << qPrintable(http->errorString()) << endl;
} else {
cerr << "File downloaded as " << qPrintable(file->fileName())
<< endl;
}
file->close();
delete file;
file = 0;
emit finished();
}
main.cpp------------------------------
#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QTextCodec>
#include <QCoreApplication>
#include <QUrl>
#include "HttpGet.h"
#include <iostream>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTextCodec::setCodecForTr(QTextCodec::codecForName("gb18030"));
HttpGet getter;
getter.downloadFile(QUrl("http://lvpengcheng.com.cn/index.htm"));
//qhttp 下载完的文件保存在哪里了?
return a.exec();
}