I have some code that successfully retrieves json content from an HTTP source:
void MainWindow::Test()
{
QNetworkRequest request;
QString filename = "http://ip.jsontest.com";
//QString filename = "https://api.github.com/users/mralexgray/repos";
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setSslConfiguration(QSslConfiguration::defaultConfiguration());
request.setUrl(QUrl(filename));
QJsonObject json;
QNetworkAccessManager nam;
QNetworkReply *reply = nam.post(request, QJsonDocument(json).toJson());
while(!reply->isFinished())
{
qApp->processEvents();
}
if (reply->error() == QNetworkReply::NoError)
{
QByteArray response_data = reply->readAll();
QJsonDocument document = QJsonDocument::fromJson(response_data);
QJsonObject object = document.object();
qDebug() << "Json File Loaded : " << filename;
qDebug() << "IP: " << object["ip"].toString();
}
else // something went wrong
{
qDebug() << "Json File Failed to Load : " << filename;
qDebug() << "Error : " << reply->errorString();
}
reply->deleteLater();
}
However, when I change the URL to the HTTPS one (the line commented out in the code) I get the error "server replied: Not Found"
The HTTPS url works fine in a browser.
In my search for answers I found many different suggestions but no actual working solution.
I believe the problem is down to QT not supporting SSL 'out of the box' due to licensing issues, but here's what I've attempted so far.
I installed "Win32OpenSSL-1_0_2h.exe"
I then copied "libeay32.dll" and "ssleay32.dll" into the QT debug folder.
I added the following to the project "pro" file:
LIBS += -LC:/OpenSSL-Win32/lib -lubsec
INCLUDEPATH += C:/OpenSSL-Win32/include
I tried with and without the setSslConfiguration call.
But all this hasn't helped.
I tested SSL with the QT method:
if (QSslSocket::supportsSsl())
{
qDebug() << "Supports SSL";
}
else
{
qDebug() << "Does NOT Support SSL";
}
and that is saying "supported".
I am building the project in QT Creator, using MSVC2012 32bit settings.
Related
In the example below sometimes the file is downloaded correctly, and sometimes, I'm getting these values in the qDebug() added into the downloadProgress lambda:
Percent complete: -1.08905e+09
Downloaded 11623330 of -1
And then the download fails, I mean it saves a zip file with 0 bytes.
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QNetworkRequest request;
// Random link just to test:
request.setUrl(
QUrl("https://github.com/FFmpeg/FFmpeg/archive/refs/tags/n5.0.2.zip"));
QNetworkReply *reply = manager->get(request);
connect(reply, &QNetworkReply::downloadProgress,
[this, reply](qint64 bytesReceived, qint64 bytesTotal)
{
qDebug() << "Downloaded " << bytesReceived << " of " << bytesTotal;
double percentComplete = (bytesReceived * 100.0) / bytesTotal;
qDebug() << "Percent complete: " << percentComplete;
});
connect(reply, &QNetworkReply::finished, [this, reply]()
{
if (reply->error() != QNetworkReply::NoError)
{
qDebug() << "Error: " << reply->errorString();
} else
{
QString fileName = "C:/Users/Raja/Downloads/file.zip";
QFile file(fileName);
if (file.open(QIODevice::WriteOnly))
{
file.write(reply->readAll());
file.close();
qDebug() << "File downloaded successfully";
} else
qDebug() << "Error: Unable to open the file";
}
reply->deleteLater();
});
What i'm missing?
Did you read the documentation?
It says that bytesTotal is -1 if the total size is unknown and
The download is finished when bytesReceived is equal to bytesTotal. At that time, bytesTotal will not be -1.
In other words: That behavior is expected and just means the download is still in progress. This probably happens when the server doesn't send a content-length header. See What's the "Content-Length" field in HTTP header?
I have a Qt application where I am trying to download a XML file form a server and then read the content of the file.
Unfortunately, I am not able to get the content of the downloaded file in to a QDomDocument.
This is what I tried
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(fileIsReady(QNetworkReply*)) );
manager->get(QNetworkRequest(QUrl("http://example.com/file.xml")));
fileIsReady(QNetworkReply *reply){
QTemporaryFile tempFile;
if(tempFile.open()){
tempFile.write(reply->readAll());
QDomDocument versionXML;
QDomElement root;
if(!versionXML.setContent(&tempFile)){
qDebug() << "failed to load version file" << endl;
}
else{
root=versionXML.firstChildElement();
//...
}
}
}
How can I achieve this?
I think the streaming interfaces are a bit hard to use when you are new to Qt. If you don't have super-big downloads that fit into RAM, just use QByteArray.
fileIsReady(QNetworkReply *reply){
QByteArray data = reply->readAll();
qDebug() << "XML download size:" << data.size() << "bytes";
qDebug() << QString::​fromUtf8(data);
QDomDocument versionXML;
if(!versionXML.setContent(data))
{
qWarning() << "Failed to parse XML";
}
// ...
}
I want to see the results of a GET request. By my understanding, this code should do it. What am I doing wrong?
void getDoc::on_pushButton_2_clicked()
{
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://www.google.com")));
}
void getDoc::replyFinished(QNetworkReply *reply)
{
qDebug() << reply->error(); //prints 0. So it worked. Yay!
QByteArray data=reply->readAll();
qDebug() << data; // This is blank / empty
QString str(data);
qDebug() << "Contents of the reply: ";
qDebug() << str; //this is blank or does not print.
}
The code compiles and runs fine. It just doesn't work.
Try modifying your replyFinished slot to look like this:
QByteArray bytes = reply->readAll();
QString str = QString::fromUtf8(bytes.data(), bytes.size());
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
You can then print the statusCode to see if you are getting a 200 response:
qDebug() << QVariant(statusCode).toString();
If you are getting a 302 response, you are getting a status redirect. You will need to handle it like this:
if(statusCode == 302)
{
QUrl newUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
qDebug() << "redirected from " + replyUrl + " to " + newUrl.toString();
QNetworkRequest newRequest(newUrl);
manager->get(newRequest);
return;
}
I'm returning when encountering a status code of 302 since I don't want the rest of the method to execute.
I hope this helps!
I want to see the results of a GET request. By my understanding, this code should do it. What am I doing wrong?
void getDoc::on_pushButton_2_clicked()
{
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://www.google.com")));
}
void getDoc::replyFinished(QNetworkReply *reply)
{
qDebug() << reply->error(); //prints 0. So it worked. Yay!
QByteArray data=reply->readAll();
qDebug() << data; // This is blank / empty
QString str(data);
qDebug() << "Contents of the reply: ";
qDebug() << str; //this is blank or does not print.
}
The code compiles and runs fine. It just doesn't work.
Try modifying your replyFinished slot to look like this:
QByteArray bytes = reply->readAll();
QString str = QString::fromUtf8(bytes.data(), bytes.size());
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
You can then print the statusCode to see if you are getting a 200 response:
qDebug() << QVariant(statusCode).toString();
If you are getting a 302 response, you are getting a status redirect. You will need to handle it like this:
if(statusCode == 302)
{
QUrl newUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
qDebug() << "redirected from " + replyUrl + " to " + newUrl.toString();
QNetworkRequest newRequest(newUrl);
manager->get(newRequest);
return;
}
I'm returning when encountering a status code of 302 since I don't want the rest of the method to execute.
I hope this helps!
I have my slot being called whenever someone clicks the link and I know the file is there because I can retrieve the file name and the amount of bytes the file is just not sure how to s ave it after I call the QFileDialog::getSaveFileName? I know that gives me the name of the file if the user decides to change it but how do I get the location they decide to save it in and then write it to that location.
NB: The file they will download is a word doc if that makes any difference?
void MainWindow::unsupportedContent(QNetworkReply *reply) {
qDebug() << "Left click - download!";
qDebug() << "Bytes to download: " << reply->bytesAvailable();
QString str = reply->rawHeader("Content-Disposition");
QString end = str.mid(21);
end.chop(1);
qDebug() << "string: " << end;
qDebug() << "File name: " << reply->rawHeader("Content-Disposition");
qDebug() << "File type: " << reply->rawHeader("Content-Type");
QString defaultFileName = QFileInfo(end).fileName();
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), defaultFileName);
if (fileName.isEmpty()) return;
QFile *file = new QFile(fileName);
file->open(fileName);
file->write(reply->read(reply->bytesAvailable()));
file->close();
}
today i explained it on another post so i will link that post here : Post
i can tell you that you have only to implement a slot that write into the file you created. and call it when readyRead() signal is emitted.