QNetworkAccessManager类允许应用程序发送网络请求和接收网络应答。
先来两个官方文档中的例子
1.QNetworkAccessManager *manager = new QNetworkAccessManager(this); connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*))); manager->get(QNetworkRequest(QUrl("http://qt-project.org")));
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<QSslError>)), this, SLOT(slotSslErrors(QList<QSslError>)));
QNetworkAccessManager *manager = new QNetworkAccessManager(this); connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*))); QString URL = "http://www.baidu.com"; /*URL.append("/...");追加数据*/ manager->get(QNetworkRequest(QUrl(URL)));
void MainWindow::replyFinished(QNetworkReply *reply) { QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); if(reply->error() == QNetworkReply::NoError) { QByteArray bytes = reply->readAll(); QString HTML(bytes); //qDebug()<<HTML; } }
QFile *file = new QFile("test.zip"); if(!file->open(QIODevice::WriteOnly)) { //qDebug()<<"文件打开出错"; delete file; file = 0; return; } startRequest(url);
void MainWindow::startRequest(QUrl url) { reply = manager->get(QNetworkRequest(url)); connect(reply,SIGNAL(readyRead()),this,SLOT(readyRead())); connect(reply,SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(updateProgress(qint64,qint64)));//更新进度条 connect(reply,SIGNAL(finished()),this,SLOT(finished()));//下载完成 } void MainWindow::readyRead() { if(file) file->write(reply->readAll()); } void MainWindow::updateProgress(qint64 bytesRead, qint64 totalBytes) { ui->progressBar->setMaximum(totalBytes); ui->progressBar->setValue(bytesRead); } void MainWindow::finished() { file->flush(); file->close(); reply->deleteLater(); reply = 0; delete file; file = 0; //qDebug()<<"下载完成"; }
QNetworkProxy proxy; proxy.setHostName("代理ip"); proxy.setPort("端口"); proxy.setType(QNetworkProxy::HttpProxy); manager->setProxy(proxy);
详情参考官方文档