Networking

Connecting to a network and retrieving resources is a basic requirement of mobile computing. With a BlackBerry 10 device, you can retrieve the cellular or Wi-Fi network status, check the network status in response to a network status event, and send and receive data over a network.

To accomplish these network-related tasks, BlackBerry 10 includes networking libraries such as libcurl, libsocket, and QtNetwork.

  • The libcurl library provides the functionality to transfer data with URL syntax, using protocols such as FILE, HTTP, IMAP, POP3, FTP, telnet, and many others.
  • The libsocket library provides support for basic sockets and TCP/IP functionality.
  • The QtNetwork library exposes a mix of low-level and high-level APIs used for sending and receiving data over a network.

QtNetwork

The QNetworkAccessManager class provides the functionality to send and receive data over a network. The image shown below demonstrates the relationship between the QNetworkAccessManager and the QNetworkRequest and QNetworkReply classes.

A flow diagram showing that data flows from QNetworkRequest to QNetworkAccessManager and then to QNetworkReply.

QNetworkRequest represents an HTTP request. At a minimum, it must contain a URL for the destination. The request can also contain HTTP headers and SSL options.

Required and option attributes of a QNetworkRequest.

QNetworkAccessManager receives network requests and sends them over the network using one of its HTTP request functions (get(), post(), put(), and so on), which returns a pointer to its QNetworkReply. These functions are all asynchronous in nature, so they do not block your main app thread.

QNetworkAccessManager also contains functionality for cookie handling, caching, and proxy handling.

The methods and attributes of a QNetworkAccessManager.

QNetworkReply represents an HTTP reply. Among other information, it contains reply data from the destination URL, HTTP headers consisting of the status code, and any errors. Data in a QNetworkReply is reported asynchronously, so you can connect to its signals and manage information as it arrives.

When new data arrives over the network, the readyRead() signal is emitted to indicate that the data is ready for reading. If you want to parse data as it arrives, you should subscribe to this signal. The readyRead() signal can be used even if you're not finished with the reply. When an HTTP request is complete, the finished() signal is emitted to indicate this event to your app.

The QNetworkReply API.

Prerequisites

To use the networking APIs in your app, you need to link to the QtNetwork module by adding the following line to your .pro file:

QT += network

Retrieve network status

When you're developing apps, you might need to know if the device is connected to a network and if that connection is either cellular or Wi-Fi.

Not applicable

You can use the classes in the QtNetwork module to find out if your device is connected to a network.

The following example demonstrates how to retrieve and listen for changes to the online status (online or offline) and the configuration type (WLAN, 2G, 3G, and so on).

// Create a QNetworkConfigurationManager object to manage 
// the network configurations and a QNetworkAccessManager to 
// find the name of the network interface

m_pNetConfigMngr = new QNetworkConfigurationManager();
m_pNetAccessMngr = new QNetworkAccessManager();

// Set up a connection between the 
// QNetworkConfigurationManager's onlineStateChanged() signal 
// to the app's onOnlineStatusChanged(bool) slot. The state 
// indicates whether the device is online or offline

bool res = QObject::connect(m_pNetConfigMngr,
           SIGNAL(onlineStateChanged(bool)),
           this,
           SLOT(onOnlineStatusChanged(bool)));

Q_ASSERT(res);

// Set up a connection between the 
// QNetworkConfigurationManager's configurationChanged()signal 
// to the app's onConfigurationChanged() slot. The  
// configuration indicates the type of connection that the  
// device has (WLAN, 2G, 3G, and so on)

res = QObject::connect(m_pNetConfigMngr,
      SIGNAL(configurationChanged(const QNetworkConfiguration &)),
      this,
      SLOT(onConfigurationChanged()));

Q_ASSERT(res);

// When the onlineStateChanged() signal is emitted,  
// get the new online status (online or offline)

void ApplicationUI::onOnlineStatusChanged(bool isOnline)
{
    // Get the 'Online' status from the onlineStateChanged()
    // signal

    QString onlineStatus = isOnline ? "Online" : "Offline";

    // Do something with the online status
}

// When the configurationChanged() signal is emitted, get the  
// new network interface
 
void ApplicationUI::onConfigurationChanged()
{
    // Retrieve the interface (WLAN, 2G, and so on) being used  
    // to make the connection

    QString intrfceNme = 
        m_pNetAccessMngr->activeConfiguration().bearerTypeName();

    // Do something with the new interface name
}

To see how the online status and network interface information can be incorporated into a UI, see Explore the Networking Downloading sample app.

Send an HTTP request

Not applicable

Here's an example that shows you how to send an HTTP GET request and retrieve the network reply. You need to create the network request and set the destination URL as a QUrl object. Then, create the network access manager, connect a custom slot to handle the finished() signal, and send the HTTP GET request.

You can define a variable m_pNetReply for various purposes, such as updating your UI and retrieving the raw headers. You can retrieve the raw headers from the m_pNetReply member variable that is set when the request is made to the server.

When the network reply has finished processing, call deleteLater() to delete the reply object and free up system resources.

// Create the network request and set the destination URL

QNetworkRequest request = QNetworkRequest();
request.setUrl(QUrl("http://www.blackberry.com"));
// Create the network access manager 

QNetworkAccessManager* m_pNetAccessMngr = 
                             new QNetworkAccessManager(this);

// Connect your custom slot to its finished() signal
// and check the return value for connection errors

bool res;
Q_UNUSED(res);

res = connect(m_pNetAccessMngr, 
              SIGNAL(finished(QNetworkReply*)),
              this,
              SLOT(onRequestFinished()));
Q_ASSERT(res);

// Use the QNetworkAccessManager object to send the HTTP 
// request and capture the reply

m_pNetReply = m_pNetAccessMngr->get(request);
void ApplicationUI::onRequestFinished ()
{
    // Check for errors and verify that data is available

    if (m_pNetReply != NULL &&
        m_pNetReply->bytesAvailable() > 0 &&
        m_pNetReply->error() == QNetworkReply::NoError)
    {
        // ...
        
        // Use the data in the m_pNetReply member variable
        // to update other components in your UI

        openFile();

        // Use the reply to set a raw headers dialog box

        QString rawHdrInfo = getRawHeaderInfo(m_pNetReply);
        m_pRawHeaderInfoTxa->setText(rawHdrInfo);

        // ...
          
        m_pNetReply->deleteLater();
    }
    else
    {
        // Handle errors here
    }
}
// Collect the raw headers and return them as a QString object

QString ApplicationUI::getRawHeaderInfo ( QNetworkReply* reply )
{
    QList <QByteArray> rawHeaderList = reply->rawHeaderList();
    QString rawHdrs;

    foreach(QByteArray hdrName, rawHeaderList)
    {
        QByteArray hdrValue = reply->rawHeader(hdrName);
        rawHdrs += hdrName;
        rawHdrs += " : ";
        rawHdrs += hdrValue;
        rawHdrs += "\n";
    }

    return rawHdrs;
}

Related resources

Last modified: 2014-09-30



Got questions about leaving a comment? Get answers from our Disqus FAQ.

comments powered by Disqus