使用QHttp下载网络文件的简单例子

场景: 

   1  可用作软件更新。

    2 文件下载服务器

 注意: 

      1 *.pro 添加 QT    +=    network 

      2 VS下,链接器---附加依赖项--输入---添加 QtNetworkd4.lib或QtNetwork4.lib,根据debug和release选择。

      3  exe目录 拷贝QtNetworkd4.dll或QtNetwork4.dll,根据debug和release选择。

      4  网络环境是在非代理下使用,否则程序需要设置代理,使用QNetworkProxy类

1 http_get.h

#ifndef HTTP_GET_H
#define HTTP_GET_H
#include <QObject>
#include <QtCore>
#include <QtGui>
#include <QtNetwork/QtNetwork>
#include <QtNetwork/QHttp>
#include <iostream>
#include <stdio.h>
#include <QUrl>
#include <QWidget>
#include <QFile>
#include <QTextStream>
#include <QNetworkAccessManager>
#include <QTextCodec>

using namespace std;

class HttpGet : public QObject
{
    Q_OBJECT
public:
    explicit HttpGet(QObject *parent = 0);
    bool getFile(const QUrl &url);
signals:
    void done();
public slots:
    void httpDone(bool error);
 private:
    QHttp http;
    QFile file;
};

#endif // HTTP_GET_H
2 http_get.cpp

#include "http_get.h"

HttpGet::HttpGet(QObject *parent) :QObject(parent)
{
    connect(&http,SIGNAL(done(bool)),this,SLOT(httpDone(bool)));
}
bool HttpGet::getFile(const QUrl &url)
{
    if(!url.isValid())
    {
         std::cerr<<"error: Invalid URL!" <<endl;
         return false;
    }
    if(url.scheme() != "http")
    {
        std::cerr<<"error: URL must start with 'http:'" <<endl;
        return false;
    }
    if(url.path().isEmpty())
    {
        std::cerr<<"error: URL has no path!" <<endl;
        return false;
    }
    QFileInfo fileInfo(url.path());
    QString localFileName = fileInfo.fileName();
    if(localFileName.isEmpty())
    {
        localFileName = "http.out";
    }
    file.setFileName(localFileName);
    if(!file.open((QIODevice::WriteOnly)))
    {
        std::cerr<<"error: Cannot write file" <<":"<<qPrintable(file.fileName())<<": "<<qPrintable(file.errorString())<<endl;
        return false;
    }
    http.setHost(url.host(),url.port(80));// 服务器端口
    http.get(url.path(),&file);
    http.close();

    return true;
}
void HttpGet::httpDone(bool error)
{
    if(error)
    {
        std::cerr<<"error:"<<qPrintable(http.errorString())<<endl;
    }
    else
    {
        std::cerr<<"file download as "<<qPrintable(file.fileName())<<endl;
    }
    file.close();
    emit done();<span style="color:#cc0000;">// 链接成功才会自动下载</span>
}

3 main.cpp

#include <QtGui/QApplication>
#include "http_get.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
	 HttpGet getter;
	 QString str("http://www.istonsoft.com/win-update.xml");
	 QUrl url(str);
     getter.getFile(url);
  
    return a.exec();
}



你可能感兴趣的:(qt,QHttp)