How to run a post request in qt main() - c++

I would like to do a simple post request int main.cpp. it would seem the when i run the application it would not execute the code and just skips it.
I tried using the qt debugger but the code below after the debugger start it just finishes right after.
I have tested my api with postman and knows it works
main.cpp
#include <iostream>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QNetworkInterface>
using namespace std;
int main()
{
QByteArray jsonString = "{\"ipaddr\": "+ QByteArray::number(9) + ",\"transactionType\":"+QByteArray::number(10) + ",\"idEmployee\":"+QByteArray::number(10) +"}";
QNetworkRequest request(QUrl("http://192.168.1.25:3000/classlog/pi"));
request.setRawHeader("Content-Type", "application/json");
QNetworkAccessManager * manager = new QNetworkAccessManager();
manager->post(request, jsonString);
}
.pro
TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
QT += network core
SOURCES += \
main.cpp
I expect that i would be able to receive the request in my server, but i am not receiving any. Thank you

Qt uses an event system. Your the network manager will only schedule a request that will be handled in an event loop. This is also where the response is received.
You need a running event loop (and in fact, a QCoreApplication object, you sould get a warning when executing your code).
#include <QtNetwork>
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QNetworkAccessManager mgr;
QNetworkRequest req(QUrl("http://stackoverflow.com"));
auto *resp = mgr.get(req);
QObject::connect(resp, &QNetworkReply::finished, [&]() {
qDebug() << "FINISHED";
if (resp->error() != QNetworkReply::NoError)
qDebug() << "Error: " << resp->errorString();
else
qDebug() << "Status: " << resp->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString();
// Stop when a response is received
app.quit();
});
// This will start the event loop that will eventually send the request and receive the response.
// It will run until you call app.quit()
return app.exec();
}

you are almost there:
connect the signals:
QtObject::connect(your_manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(onResult(QNetworkReply *)));
send something:
QNetworkRequest request(your_URL);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QByteArray byteArray;
byteArray.append(your_json);
your_manager->post(request, byteArray);
read the answer in the slot:
void FOO_CLASS::onResult(QNetworkReply* reply)
{
QString resp = QString::fromUtf8(reply->readAll());
}
edit
:
QObject::connect(your_manager, &QNetworkAccessManager::finished, [](QNetworkReply * r){
QString x{r->readAll()};
//foo1
auto l{x.length()};
//foo2
});

Related

Multiple get/post calls using a wrapper class with Qt

I am working on a Qt project with a team. I have two functions — one retrives the numerical coordinates of a place, the other downloads the map of the place — that I want to merge in one wrapper class, so that my teammates can call it easily.
#include <QCoreApplication>
#include <QFile>
#include <QHttpMultiPart>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <iostream>
class OpenStreetMapWrapper: public QObject{
Q_OBJECT
public:
OpenStreetMapWrapper(QObject *parent=nullptr):QObject(parent){
connect(&manager, &QNetworkAccessManager::finished, this, &OpenStreetMapWrapper::handle_finished);
}
void download(const std::string &region, const std::string &department, const QFile& outfile){
QNetworkRequest request;
QUrl url = QUrl(QString::fromStdString("https://download.openstreetmap.fr/extracts/europe/france/" + region + "/" + department + ".osm.pbf"));
request.setUrl(url);
request.setAttribute(QNetworkRequest::User, outfile.fileName());
manager.get(request);
}
void searchCSV(QFile& file, QFile& outfile){
QNetworkRequest request(QUrl("https://api-adresse.data.gouv.fr/search/csv/")); // Free API provided by the French government
request.setAttribute(QNetworkRequest::User, outfile.fileName());
QHttpMultiPart *multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart postpart;
postpart.setHeader(QNetworkRequest::ContentDispositionHeader,
QString("form-data; name=%1; filename=%2")
.arg("data", file.fileName()));
postpart.setBodyDevice(&file);
multipart->append(postpart);
file.setParent(multipart);
manager.post(request, multipart);
}
private:
QNetworkAccessManager manager;
void handle_finished(QNetworkReply *reply){
if(reply->error() == QNetworkReply::NoError){
QByteArray read = reply->readAll();
std::cout << read.toStdString() << std::endl; // For debugging
QString filename = reply->request().attribute(QNetworkRequest::User).toString();
QFile out(filename);
if(out.open(QIODevice::WriteOnly)){
out.write(read);
out.close();
}
}
else{
qDebug() << reply->error() << reply->errorString();
}
reply->deleteLater();
// QCoreApplication::quit(); This is done somewhere else?
}
};
#include <main.moc>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
OpenStreetMapWrapper A;
QFile file("./search.csv");
file.open(QIODevice::ReadWrite);
QFile outfile("./output.csv");
outfile.open(QIODevice::ReadWrite);
// Search
A.searchCSV(file, outfile); // 1st call works
A.searchCSV(file, outfile); // 2nd call -> makes both calls fail.
// Downloader
std::string region = "corse";
std::string department = "haute_corse";
return a.exec();
}
The problem with the code above, is that when for example searchCSV is called it displays the output as needed, but if it is called twice in the code, there is no output at all. After some debugging I think the problem is that the manager and handle_finished are not connected properly, because the execution never reaches there. Is there a simple way to solve this issue? Ideally, there is just one class instant, and any method can be called any number of times.
I don't know much about Qt, but it looks like you're trying to read from file twice and my guess is that when it reaches the end of the file after the first call to A.searchCSV it is done and you can't read from it anymore - unless you reposition the QFile to the beginning of the file.
Possible solution:
A.searchCSV(file, outfile);
file.unsetError(); // possibly needed
file.seek(0); // rewind to the start of the file
A.searchCSV(file, outfile);
The two QFile (input, output) are shared between two asynchronous calls (searchCSV) that might give an undefined behavior. The input file (stream) contents will be load and push only after the connection was made (like curl does).
You should:
Make searchCSV a blocking function (wait until handle_finished() done), input file pointer should be reinitialized before an other call.
OR: Use separated input/output QFile instances

Memory access error when using QNetworkManager

I'm fairly new to C++ (though I have some experience with C) as well as QT. I'm trying to make a program that POSTs to a website when the user clicks a button, but whenever I try to access QNetworkManager I get a memory access error.
The code for my request object is as follows (trimmed slightly to show the important bits):
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include "cJSON.h"
class unifiedRequests: public QObject {
Q_OBJECT
public:
// Members
QString access_token = "";
bool admin = false;
// Methods
explicit unifiedRequests(QObject *parent=0);
QNetworkReply* login_request(QString *email, QString *password);
signals:
public slots:
void login_complete(QNetworkReply *reply);
void sslErrorHandler(QNetworkReply*, const QList<QSslError> & );
private:
QNetworkRequest make_headers(QByteArray endpoint);
QNetworkRequest make_headers(QByteArray endpoint, QByteArray *access_token);
};
QNetworkRequest unifiedRequests::make_headers(QByteArray endpoint) {
QString url = endpoint.prepend("https://dali.vpt.co.uk");
QNetworkRequest request = QNetworkRequest(url);
qDebug() << "Setting Headers";
request.setRawHeader("User-Agent", "Desktop Client Debug");
request.setRawHeader("Content-Type", "application/json");
qDebug() << "Set headers successfully.";
return request;
}
void unifiedRequests::sslErrorHandler
(QNetworkReply* reply, const QList<QSslError> & errors) {
qDebug() << "Ignoring SSL Errors";
};
QNetworkReply* unifiedRequests::login_request
(QString *email, QString *password) {
QNetworkRequest request = make_headers("/api/auth");
qDebug() << "Making JSON";
cJSON *login_json; //The body of the request
login_json = cJSON_CreateObject();
cJSON_AddStringToObject(login_json, "email", email->toUtf8());
cJSON_AddStringToObject(login_json, "password", password->toUtf8());
qDebug() << "Made JSON: ";
qDebug() << cJSON_Print(login_json);
QNetworkAccessManager *manager = new QNetworkAccessManager;
//The object we use to send the request and receive the reply
qDebug() << "Turning off SSL";
connect(manager,
SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError> & )),
this,
SLOT(sslErrorHandler(QNetworkReply*, const QList<QSslError> & )));
qDebug() << "POSTing login.";
QNetworkReply *reply = manager->post(request, cJSON_Print(login_json));
qDebug() << "Connecting signal to slot.";
QAbstractSocket::connect(manager, SIGNAL(finished(QNetworkReply * )),
this, SLOT(login_complete(QNetworkReply * )));
cJSON_Delete(login_json);
return reply;
}
I'm creating the unifiedRequests object by calling:
unifiedRequests requestObj;
in a different file. It crashes out on the line where I try to turn off SSL (we're using a self-signed certificate, so I need to do this in order to make the request). Any thoughts?
Thank you!
You create the unifiedRequests object by calling "unifiedRequests requestObj;", this object will be deleted when the variable "requestObj" goes out of scope.
So, when the signal will be received, the object will be already destroyed.
Try to create your unifiedRequests object by calling "unifiedRequests* requestObj = new unifiedRequests();".
Of course, you need to call "delete requestObj;" somewhere to destroy this object. Where and when depend on your application (when you don't need this object anymore).
To understand the difference, look at here : http://www.tutorialspoint.com/cplusplus/cpp_dynamic_memory.htm
Or google for "C++ heap / stack / dynamic allocation"

Looping through QNetworkAccessManager get() routines, retrieve order on finish

I have a QNetworkAccessManager as a member of my class. I connect the finished signal from this manager to the replyFinished function I have written.
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));
In a separate routine, I loop through a get call from the manager
for (int si = 0; si<numLines; si++)
{
QString line = lines[si];
manager->get(QNetworkRequest(QUrl(line)));
}
In my replyFinished slot routine, I know I may not receive the signals in the order they were performed in the loop, but is there any way I can obtain that information? That is, is there a clever way I can obtain "si" in my replyFinished routine? Thanks for the help!
QNetworkAccessManager::get() returns a pointer to the QNetworkReply object. This pointer is the same one that is passed your replyFinished() slot. You can use a QMap to store pairings of QNetworkReply* pointers and integers (si in your code).
Here is a working example;
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QUrl>
#include <QMap>
#include <QtDebug>
QNetworkAccessManager am;
void finished(QNetworkReply* reply);
QMap<QNetworkReply*, int> requests;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QObject::connect(&am, &QNetworkAccessManager::finished, finished);
QStringList links;
links << "http://google.com";
links << "http://taobao.com";
links << "http://stackoverflow.com";
links << "http://stackexchange.com";
links << "http://bing.com";
for (int i=0; i < links.size(); i++)
{
requests.insert(am.get(QNetworkRequest(QUrl(links[i]))), i);
}
return a.exec();
}
void finished(QNetworkReply* reply)
{
qDebug() << requests[reply];
}
The slot replyFinished(QNetworkReply*) receives pointer to the related reply object. This reply object contains all information about that reply (error code, headers, downloaded data, the URL of the content) and also it contains initial request (QNetworkReply::request()). So, it is possible to check the URL of the request or the URL of actual downloaded content. Note that those URLs may be different.
QNetworkReply::url():
Returns the URL of the content downloaded or uploaded. Note that the
URL may be different from that of the original request.
QNetworkReply::request():
Returns the request that was posted for this reply. In special, note
that the URL for the request may be different than that of the reply.
void MainWindow::replyFinished(QNetworkReply* reply)
{
qDebug() << reply->url();
qDebug() << reply->request().url();
}

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.

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);
}