Retrieving data from web with QNetworkAccessManager: the file is downloaded but QNetworkReply::readAll returns null - c++

There has been the same question already, but the single answer is not helpful: Qt Download File - QNetworkAccessManager, not getting data
So, I'm trying to download a file:
QNetworkRequest request;
request.setUrl(QUrl(fileUrl));
QNetworkReply * reply = m_nam.get(request);
connect(reply, SIGNAL(finished()), this, SLOT(onDownloadRequestFinished()), Qt::UniqueConnection);
connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(onDownloadRequestProgress(qint64, qint64)), Qt::UniqueConnection);
And in the onDownloadRequestFinished slot:
QNetworkReply * reply = qobject_cast<QNetworkReply *>(sender());
if (reply && reply->error() == QNetworkReply::NoError) {
Q_ASSERT(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 200);
qDebug() << "reply " << reply->bytesAvailable() << reply->pos() << reply->size() << reply->isReadable() << reply->openMode() << reply->isOpen();
}
The slot prints the following: reply 0 0 0 true OpenMode( "ReadOnly" ) true
So, no data. However, I can clearly see that it does download something somewhere. It's a big file and it does download it, judging from onDownloadRequestProgress.
Important clarification: pretty much the same code works in another project on the same computer. I'm trying to find differences, but see none so far.
Where's the data?

Did you connected readyRead() signal to write bytes received into a specific file?
I always did this to save a file:
const QNetworkRequest& request = QNetworkRequest(url);
reply = qnetworkaccessmanager->get(request);
QObject::connect(reply, SIGNAL(readyRead()), this,
SLOT( readingReadyBytes() ));
then i create my slot:
void yourClass::readingReadyBytes() {
file->write(reply->read(reply->bytesAvailable()));
}

Related

How do I read the data from QNetworkReply?

How do I read the data from a QNetworkReply response from a specific URL before QWebPage does? but when the finished() signal is emited the reply is read already by QWebPage, so connect readyRead() or call reply->readAll() return nothing. I tried overload acceptNavigationRequest() method in my own QWebPage class, something like this:
bool webPage::acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, QWebPage::NavigationType type)
{
//qDebug() << "filename = " << request.rawHeader("content-disposition");
if(request.url().path() == QStringLiteral("download.php"))
{
QNetworkReply *reply = networkAccessManager()->get(request);
QFile file;
file.setFileName(filename);
if(!file.open(QIODevice::ReadWrite))
{
/* handle error */
}
file.write(reply->readAll());
file.close();
return false;
}
But I couldn't manage to reply work... the returned reply is invalid (don't even return a http status code, I know it means the http request sent is invalid but i don't know why).
Different approachs to solve this are welcome!
Using the finished slot with a lambda expression, you can do this: -
QNetworkReply* reply = networkAccessManager()->get(request);
connect(reply, &QNetworkReply::finished, [=]() {
if(reply->error() == QNetworkReply::NoError)
{
QByteArray response = reply->readAll();
// do something with the data...
}
else // handle error
{
qDebug(pReply->errorString());
}
});

File download - check for error before file write

I'm using Qt to download a file from HTTP, for that, I'm using two signals:
connect(currentDownload, SIGNAL(finished()),
SLOT(downloadFinished()));
connect(currentDownload, SIGNAL(readyRead()),
SLOT(downloadReadyRead()));
Callbacks:
void DownloadManager::downloadFinished()
{
output.close();
if (currentDownload->error()) {
// download failed
std::cout << "Failed: [" << currentDownload->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()
<< "] " << qPrintable(currentDownload->errorString()) << std::endl;
} else {
std::cout << "Download succeeded" << std::endl;
}
currentDownload->deleteLater();
startNextDownload();
}
void DownloadManager::downloadReadyRead()
{
output.write(currentDownload->readAll());
}
The problem I'm having is that I cant figure out how to skip writing the output file, if any error has occured during download for whatever reason. This is not logical - since I can only check for error during the finished() signal emitting. Checking for errors during the readyRead() signal won't show any, even though they exist. In the results, 404 output file will be written to the disk. How can I solve that?
You should use QNetworkRequest to get all the infromation.
Refer to this example.
QNetworkAccessManager provide more signals to tackle errors.
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>)));

How to use QNetworkManager for REST api?

I would like to make a class for accessing data via REST API, for example:
class MeteoStation{
int getLatestTemperature();
int getLatestPessure();
private:
QNetworkManager nmng;
}
How could I implement this methods? Usually I was using something like:
int MeteoStation::getLatestTemperature(){
...
QEventLoop eventLoop;
connect(&m_nam,SIGNAL(finished(QNetworkReply*)),&eventLoop,SLOT(quit()));
QNetworkReply *reply = m_nam.get( req );
eventLoop.exec();
reply->readAll()
...
}
But since using inner QEventLoop is not recommended, how should I see to whom the response belong to?
MeteoStation::MeteoStation(){
connect(&nmam, SIGNAL(finished(QNetworkReply*)),
this, SLOT(parseNetworkResponse(QNetworkReply*)));
}
void MeteoStation::parseNetworkResponse( QNetworkReply *finished )
{
QByteArray data = finished->readAll();
...
Yes and it would be nice to have the class thread save. How are you solving that in your code?
How bad is making the call synchronous with:
QNetworkRequest req(url);
QScopedPointer<QNetworkReply> reply(nam.get(req));
QTime timeout= QTime::currentTime().addSecs(10);
while( QTime::currentTime() < timeout && !reply->isFinished()){
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
if (reply->error() != QNetworkReply::NoError) {
qDebug() << "Failure" <<reply->errorString();
}
QByteArray data = reply->readAll();
I've resolved my problem using QCoreApplication::processEvents(). The response is there within ms and I'm able to implement functionality close to libcurl.
QNetworkRequest req(url);
QScopedPointer<QNetworkReply> reply(nam.get(req));
QTime timeout= QTime::currentTime().addSecs(10);
while( QTime::currentTime() < timeout && !reply->isFinished()){
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
if (reply->error() != QNetworkReply::NoError) {
qDebug() << "Failure" <<reply->errorString();
}
QByteArray data = reply->readAll();
The Qt docs should provide all info you need.
You creat a nam, connect the finished signal, send the request.
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(parseNetworkResponse(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://qt-project.org")));
Detecting to which request a reply belongs should not be too hard. The reply contains the url. It might be different, but not that different:
...but for a variety of reasons it can be different (for example, a
file path being made absolute or canonical).
QUrl QNetworkReply::url() const
Returns the URL of the content downloaded or uploaded. Note that the
URL may be different from that of the original request.

Simple version checker with Qt

I’m trying to implement a simple version checker below.
I’m getting a zero error code reading the file, but the file
contents show up blank. You can access the file via browser,
permissions are ok.
void check_version()
{
QNetworkAccessManager *nam = new QNetworkAccessManager();
QUrl data_url("http://www.example.com/version.txt");
QNetworkRequest req(data_url);
QNetworkReply *reply = nam->get(req);
QByteArray data = reply->readAll() ;
QString s1(data);
int err = reply->error();
QString s2 = QString::number(err);
delete reply;
delete nam;
QMessageBox::critical(0, "",s1+" "+s2,QMessageBox::Cancel);
}
I gather the problem is that I need to wait to read until the get is finished, so I need a signal and a slot: the signal tells the slot to read the data.
pseudocode:
QObject::connect(&rep, SIGNAL( rep is finished ),
QByteArray newver , SLOT( reply->readAll() ));
How do I set up a signal/slot for my task?
You're right, you have to wait until the get() is "finished" in order to obtain the whole response with a call to readAll().
Following a working example to start with:
// ...
QNetworkAccessManager *nam = new QNetworkAccessManager();
QUrl data_url("http://www.example.com/version.txt");
QNetworkReply* reply = nam->get(QNetworkRequest(data_url));
QEventLoop eventLoop;
QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
eventLoop.exec();
if (reply->error() != QNetworkReply::NoError)
{
// Something went wrong. Error can be retrieved with: reply->error()
}
else
{
// Call reply->readAll() and do what you need with the data
}
// ...
This example will block until the reply is ready. If you need an asynchronous behavior you can just connect the signal finished() to a custom slot and check for error and/or read there. I do not recommend to connect the signal finished() directly to readAll() because "sometimes errors happen".

Qt Download File - QNetworkAccessManager, not getting data

I'm trying to have my application download a file from a URL, typically an EXE or a Jar, not that this should change much though. I have this all running in a thread, but I don't think that will make a difference (if it does let me know).
So Do_Download is my function that creates the manager, sets the URL and request, and performs get. I then try to connect the finished signal to the slot the will write the file.
void DownloadManager::Do_Download() {
QNetworkAccessManager *netManager = new QNetworkAccessManager(this);
QUrl url(install_mirror); //istall_mirror is the URL provided by user
QNetworkRequest req(url);
QNetworkReply *reply = netManager->get(req);
connect(reply, SIGNAL(finished()), this, SLOT(writeData()));
}
My writeData function checks for errors, and if there are no errors it writes the data to file.
void DownloadManager::writeData() {
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
if (reply) {
if (reply->error() == QNetworkReply::NoError) {
QFile file(location);
if(file.open(QIODevice::WriteOnly)) {
file.write(reply->readAll());
} else {
errorMessage = "Error writing downloaded file for mirror installation";
}
} else {
//get http status code
int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
errorMessage = "HTTP Error code while downloading from mirror: " + httpStatus;
}
reply->deleteLater();
} else {
errorMessage = "Error downloading file from installation mirror";
}
}
The problem being there is no data being written. It just creates a 0Kb file.
I tried adding a download progress slot so I could see what was going on recieving the data. So I added this to my Do_Download method.
connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(DL_Progress(qint64,qint64)));
void DownloadManager::DL_Progress(qint64 recieved, qint64 total) {
std::cout << recieved << " / " << total << endl;
}
The output displays one time as 0 / 01
What am I doing wrong?
The only problem I see in your code is you are not waiting for the download to be finished. The NetworkRequest object would be destructed at the end of function call.
So, I would rewrite Do_Download like this (QEventLoop syncronizes the network request):
void DownloadManager::Do_Download() {
QEventLoop eventLoop;
QNetworkAccessManager *netManager = new QNetworkAccessManager(this);
QUrl url(install_mirror); //istall_mirror is the URL provided by user
QNetworkRequest req(url);
QNetworkReply *reply = netManager->get(req);
connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
eventLoop.exec();
writeData(reply);
}