QNetworkAccessManager 异步API
最后更新于:2022-04-02 02:15:04
[TOC]
## 概述
QNetworkAccessManager是一套API库,可以发包,设置代理,内存配置等。可以用于网络的应答(如http协议)。
1. 当请求完成后,用户需要手动删除QNetworkReply对象,这里要注意,不应该在finished()信号过来的时候删除,而应该使用deleteLater()函数。
2. 如果要并行处理,这里取决于平台,目前桌面平台支持6个并行。
## 示例
### 异步读取
```
#include "widget.h"
#include "ui_widget.h"
#include
#include
#include
#include
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
m_manager = new QNetworkAccessManager(this);
connect(m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
QUrl url("http://www.baidu.com");
m_netWorkReply = m_manager->get(QNetworkRequest(url));
connect(m_netWorkReply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(netWorkReplyLoadProgress(qint64,qint64)));
connect(m_netWorkReply, SIGNAL(readyRead()), this, SLOT(httpRead()));
}
Widget::~Widget()
{
delete ui;
}
void Widget::replyFinished(QNetworkReply *reply)
{
qDebug() << "reply->readAll():" << QString::fromUtf8(reply->readAll());
m_netWorkReply->deleteLater(); //此列子中 m_netWorkReply->deleteLater(); 与 delete m_netWorkReply; 没有什么区别
}
void Widget::netWorkReplyLoadProgress(qint64 received, qint64 total)
{
qDebug() << "received:" << received << " total:" << total;
}
void Widget::deleteNetWorkReply()
{
qDebug() << "deleteNetWorkReply called!" << endl;
}
void Widget::httpRead()
{
qDebug() << "httpRead";
}
```
### User-Agent
```
QNetworkRequest request;
request.setUrl(QUrl("http://qt-project.org"));
request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
QNetworkReply *reply = manager->get(request);
connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(slotError(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(sslErrors(QList)),
this, SLOT(slotSslErrors(QList)));
```
';