While developing our Blackberry 10 app, we had reached a point in the project where we now needed to make web service calls. As other components of the app will need this service, it made sense just to create a network manager class. Initially I was unsure how this would work with signals and slots, but was pleasantly surprised at how straight forward this was. RIM had already posted a great
Tutorial and some documentation regarding
QNetworkAccessManager so I was already in good shape. Although the tutorial is very good, I thought it would be beneficial to strip out the other stuff and just show the bare bones of making a web service call and listening for a response was done.
In my NetworkManager.hpp:
#include <QObject>
class NetworkManager : public QObject
{
Q_OBJECT
public:
NetworkManager();
virtual ~NetworkManager();
void makeRequest(QString URL);
private slots:
//Handles the network reply.
void requestFinished(QNetworkReply* reply);
private:
QNetworkAccessManager *mNetworkAccessManager;
QFile *mFile;
}
In my NetworkManager.cpp file
NetworkManager::NetworkManager()
{
//Instantiate my mNetworkAccessManager
mNetworkAccessManager = new QNetworkAccessManager(this);
//Setup up my signal and slots.
//Notice I did not declare a signal for “finished” in my header file. This is because
// QNetworkAccessManager will fire off this signal.
bool result = connect(mNetworkAccessManager,
SIGNAL(finished(QNetworkReply*)), this,
SLOT(requestFinished(QNetworkReply*)));
// Displays a warning message if there's an issue connecting the signal
// and slot. This is a good practice with signals and slots as it can
// be easier to mistype a slot or signal definition
Q_ASSERT(result);
Q_UNUSED(result);
}
//Call this public function with a URL to make a request.
void NetworkManager::makeRequest(QString URL)
{
QNetworkRequest request = QNetworkRequest();
request.setUrl(QUrl(URL));
mNetworkAccessManager->get(request);
}
//And finally the response from the server. The important item to mention here is that you
//have set up the slot requestFinished(…) in your header file.
void NetworkManager::requestFinished(QNetworkReply* reply)
{
// Check the network reply for errors
if (reply->error() == QNetworkReply::NoError)
{
QString fileName = QString("%1%2").arg( appPath, "output.json");
// Create a file in the application's data directory
mFile = new QFile(fileName);
// Open the file and print an error if the file cannot be opened
if (!mFile->open(QIODevice::ReadWrite))
{
qDebug() << "\n Failed to open file";
return;
}
// Write to the file using the reply data and close the file
mFile->write(reply->readAll());
mFile->flush();
mFile->close();
}
else
{
qDebug() << "\n Problem with the network";
qDebug() << "\n" << reply->errorString();
}
}
Leave a comment