Skip to content

Instantly share code, notes, and snippets.

@antekone
Created April 1, 2014 12:35
Show Gist options
  • Save antekone/9913064 to your computer and use it in GitHub Desktop.
Save antekone/9913064 to your computer and use it in GitHub Desktop.
QNetworkAccessManager example
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <stdint.h>
#include <vector>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QNetworkAccessManager *mgr = new QNetworkAccessManager(this);
QNetworkRequest req;
req.setUrl(ui->lineEdit->text());
req.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36");
resp = mgr->get(req);
connect(resp, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
connect(resp, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(slotError(QNetworkReply::NetworkError)));
connect(resp, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(slotSslErrors(QList<QSslError>)));
}
void MainWindow::slotReadyRead() {
std::vector<char> buf;
qint64 chunk;
QString allbuf;
while(resp->bytesAvailable() > 0) {
chunk = resp->bytesAvailable();
if(chunk > 4096)
chunk = 4096;
buf.resize(chunk + 1);
memset(& buf[0], 0, chunk + 1);
if(chunk != resp->read(& buf[0], chunk)) {
ui->textBrowser->appendPlainText("-> read error");
} else {
ui->textBrowser->appendPlainText("-> read ok");
}
allbuf += & buf[0];
}
ui->textBrowser->setPlainText(allbuf);
}
void MainWindow::slotError(QNetworkReply::NetworkError) {
}
void MainWindow::slotSslErrors(QList<QSslError>) {
}
@setebe
Copy link

setebe commented Jul 27, 2019

Where resp come from in 25 th line?

@antekone
Copy link
Author

It was 5 years ago and I don't have the original code anymore, but it looks like resp is a field inside MainWindow class (so it should be in MainWindow.h), as well as it's type is QNetworkReply * (I think).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment