首先需要pro里面加上network
QT += core gui network
第一种方法
一,获取LineEdit网址内容并传值
QString url=ui->lineEdit->text();
manager->get(QNetworkRequest(QUrl(url)));
二,连接信号
connect(manager,SIGNAL(finished(QNetworkReply *)),this,SLOT(doProcessFinished(QNetworkReply *)));
三,打印出内容
QString str=reply->readAll();
ui->textEdit->setText(str);
代码:
.h代码
private slots:
void buttonnn();
void doProcessFinished(QNetworkReply *reply)
private:
QNetworkAccessManager *manager;
QNetworkReply *reply;
void Init();
.cpp代码:
void Widget::Init() //需要添加到主函数里
{
manager=new QNetworkAccessManager(this);
connect(manager,SIGNAL(finished(QNetworkReply *)),this,SLOT(doProcessFinished(QNetworkReply *)));
}
void Widget::buttonnn() //需要连接信号槽
{
QString url=ui->lineEdit->text();
manager->get(QNetworkRequest(QUrl(url)));
}
void Widget::doProcessFinished(QNetworkReply *reply)
{
QString str=reply->readAll();
qDebug()<<str;
ui->textEdit->setText(str);
}
第二种方法
比第一种主要多了一个判断错误的方法。
errorr(QNetworkReply::NetworkError error)
.h代码
private slots:
void buttonnn();
void doRead();
void errorr(QNetworkReply::NetworkError);
void doFinished();
private:
QNetworkAccessManager *manager;
QNetworkReply *reply;
void Init();
.cpp代码
void Widget::Init()
{
manager= new QNetworkAccessManager(this);
}
void Widget::buttonnn()
{
QNetworkRequest request;
request.setRawHeader(QByteArray("wqeqeqq"),QByteArray("vvvvvvvv"));
QString url=ui->lineEdit->text();
QUrl s;
s.setUrl(url);
request.setUrl(s);
reply=manager->get(request);
connect(reply ,SIGNAL(readyRead()),this,SLOT(doRead()));
connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(errorr(QNetworkReply::NetworkError)));
connect(reply,SIGNAL(finished()),this,SLOT(doFinished()));
}
void Widget::doRead()
{
QString str=reply->readAll();
ui->textEdit->setText(str);
}
void Widget::errorr(QNetworkReply::NetworkError error)
{
switch ((int)error) {
case QNetworkReply::ContentGoneError:
qDebug()<<11111;
case QNetworkReply::ContentReSendError:
qDebug()<<2222;
default:
break;
}
}
void Widget::doFinished()
{
qDebug()<<3333;
}
下载:
主要增加了这一个函数
void Widget::doRead()
{
while(!reply->atEnd())
{
QByteArray ba=reply->readAll();
myfile->write(ba);
}
}
文件打开写入
QStringList list=url.split("/");
QString filename=list.at(list.length()-1);
myfile->setFileName(filename);
bool ret=myfile->open(QIODevice::WriteOnly |QIODevice::Truncate);
设置进度条的函数
void Widget::downLoad(qint64 Recv,qint64 all)
{
ui->progressBar->setMaximum(all);
ui->progressBar->setValue(Recv);
}
进度条初始化
ui->progressBar->setValue(0);
ui->progressBar->setMinimum(0);