QT--HTTP图片下载器
1.http使用前提
QT += core gui network
2.必须头文件
#include <QNetworkAccessManager> //三个http必须头文件
#include <QNetworkReply>
#include <QNetworkRequest>
3.widget.h文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QPainter>
#include <QPoint>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
QPixmap pixmap;
QPainter *painter; //绘制显示图片
QNetworkAccessManager *manager;
QNetworkReply *reply;
void paintEvent(QPaintEvent *event); //绘图
void Init();
private slots:
void doProcessReadyRead();
void on_pushButton_clicked();
void doProceesFinished();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
4.widget.cpp文件
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QFile>
#include <QPixmap>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
Init();
}
Widget::~Widget()
{
delete ui;
}
void Widget::Init()
{
manager = new QNetworkAccessManager(this);
}
void Widget::doProcessReadyRead() //读取储存图片
{
qDebug()<< "123456";
QByteArray str = reply->readAll();
qDebug() << str;
ui->textEdit->append(str);
qDebug() << pixmap.loadFromData(str);
pixmap.save(QString("E:/test.jpg"), "jpg");
QString path = "E:/1.jpg"; //打开/创建文件
QFile file(path);
if (!file.open(QIODevice::WriteOnly|QIODevice::Append))
{
qDebug() <<"打开失败";
return;
}
else
{
file.write(str);
}
}
void Widget::paintEvent(QPaintEvent *event) //绘制图片
{
painter = new QPainter(this);
QRectF target(0,0, this->width(), this->width());
QRectF source(0,0, this->width(), this->width());
QPixmap pixmap_background("E:/1.jpg");
painter->drawPixmap(target, pixmap_background, source);
update();
}
void Widget::on_pushButton_clicked()
{
QNetworkRequest requst;
requst.setRawHeader(QByteArray("User-Agent"), QByteArray("Sun, 06 Nov 1994 08:49:37 GMT")); //设置头
QString url_str = ui->lineEdit->text();
QUrl url;
url.setUrl(url_str);
requst.setUrl(url);
reply = manager->get(requst); //发送请求
connect(reply, &QIODevice::readyRead, this, &Widget::doProcessReadyRead); //收到可读信号
connect(reply, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error), //收到异常信号
[=](QNetworkReply::NetworkError code)
{
switch((int)code)
{
case QNetworkReply::ConnectionRefusedError:
qDebug() << "远程服务器拒绝连接(服务器不接受请求)";
break;
case QNetworkReply::HostNotFoundError:
qDebug() << "找不到远程主机名(无效的主机名)";
break;
case QNetworkReply::TimeoutError:
qDebug() << "与远程服务器的连接超时";
break;
default:
break;
}
});
connect(reply, &QNetworkReply::finished,this,&Widget::doProceesFinished);
}
void Widget::doProceesFinished()
{
qDebug() <<"结束";
}
5.widget.ui文件