Sorry about the red box, but we really need you to update your browser. Read this excellent article if you're wondering why we are no longer supporting this browser version. Go to Browse Happy for browser suggestions and how to update.

Generic Connection Framework

If you develop apps for smartphone users who are running BlackBerry Device Software 4.7 or earlier, you need to use the GCF to open a network connection. However, any code that you write that uses the GCF also runs on later versions of BlackBerry Device Software. The GCF is implemented in the javax.microedition.io.Connector class. You can call Connector.open() to create any type of supported connection. The open() method accepts a connection string that specifies the type of connection to make, the end point, and optional configuration details for the connection.

The connection string that is used by the GCF has three parts:

<scheme> : <hierarchical -location-information> ; <additional -information>

where:

  • <scheme> is the protocol to use to establish the connection.
  • <hierarchical -location-information> describes the end point for the connection.
  • <additional -information> controls the transport that is used and provides authentication details for a proxy server if they are required.

In the following example, the connection string specifies the HTTP protocol and uses a host name to indicate the connection end point. The interface=wifi parameter is included to specify that the Wi-Fi radio should be used to establish the connection.

HTTPConnection c = (HTTPConnection)Connector.open("http://example.com;interface=wifi");

Open a network connection using the GCF

Make sure that the transport that you want to use is available and has coverage.

The following example shows you how to open an HTTP connection using the BlackBerry Mobile Data System transport. You can use a similar process to open a connection using other protocols and transports.
CAUTION:
The Connector.open() method is not thread-safe. Ensure that you invoke open() on a thread that is separate from the main event thread.

Import the required classes and interfaces.

import net.rim.device.api.ui.UiApplication;
import java.io.IOException;
import javax.microedition.io.*;

Create a new thread to open the connection.

Thread t = new Thread(new Runnable()
{
    public void run()
    {

Create a local variable for your Connection object.

        Connection conn = null;

Invoke open(). Specify the connection string.

        try
        {
            conn = Connector.open("http://www.blackberry.com;deviceside=false");
        } catch (IOException e)
        {
            // Process your error condition
        }

If the connection attempt was successful, open() returns a Connection object that you can use. Pass the connection object to a method that is responsible for displaying the content.

        if (conn != null)
        {
            displayContent(conn);
        }
    }
});

Start your thread.

t.start();

Implement displayContent(). In this case, push a screen that uses a Connection parameter to retrieve and display the content, after the connection retrieval thread completes.

private void displayContent(final Connection conn) 
{
    UiApplication.getUiApplication().invokeLater(new Runnable()
    {
        public void run() {
            UiApplication.getUiApplication().pushScreen(new HTTPOutputScreen(conn));
        }
    });
}

Send and receive data using a network connection

Open a network connection and pass a Connection object to the constructor of the class that is developed in this task.

The following example shows you how to send and receive data using an HTTP connection to a web site. The data that is returned from the web site is displayed on the screen. You can use a similar process to send and receive data using other network protocols. To make this task as general as possible, the following code sends an HTTP GET command manually to a server. Normally, you would use an HttpConnection interface, which constructs the HTTP command string according to the options that you configure.
CAUTION:
Network input and output operations are not thread-safe. Make sure that you create a separate thread when you use a Connection object.

Import the required classes and interfaces.

import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.UiApplication;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.*;

Create a class that extends the MainScreen class.

public class HTTPOutputScreen extends MainScreen 
{

Create an instance variable for a RichTextField object to display the results.

RichTextField _rtfOutput = new RichTextField();

Create a constructor that accepts a Connection object as an argument.

public HTTPOutputScreen(Connection conn)
{

Add the RichTextField to your screen, and start a thread to access the network connection.

_rtfOutput.setText("Retrieving data. Please wait...");
add(_rtfOutput);
ContentReaderThread t = new ContentReaderThread(conn);
t.start();

Create a method to populate your RichTextField with the data that is returned from the web site, after ContentReaderThread completes.

public void showContents(final String result) 
{
    UiApplication.getUiApplication().invokeLater(new Runnable() {

        public void run() {
            _rtfOutput.setText(result);
        }
    });
}

In an inner class, create a thread to communicate with the web server. Accept a ConnectionDescriptor object as an argument.

private final class ContentReaderThread extends Thread
{
    private Connection _connection;

    ContentReaderThread(Connection conn)
    {
        _connection = conn;
    }
    public void run()
    {

Initialize an OutputStream object and an InputStream object to exchange data with the web site.

    OutputStream os = null;
    InputStream is = null;

Initialize a String object to store the response from the web site.

    String result = "";

Create an OutputConnection object to send data over your connection.

    try
    {
        OutputConnection outputConn = (OutputConnection) connection;

Retrieve an OutputStream from your OutputConnection.

        os = outputConn.openOutputStream();
        String getCommand = "GET " + "/" + " HTTP/1.0\r\n\r\n";
        os.write(getCommand.getBytes());
        os.flush();

Send an HTTP GET command to the web server over your OutputStream. Convert the GET command into a byte array.

        String getCommand = "GET " + "/" + " HTTP/1.0\r\n\r\n";
        os.write(getCommand.getBytes());
        os.flush();

Create an InputConnection object to receive data from your connection.

        InputConnection inputConn = (InputConnection) connection;

Retrieve an InputStream from your InputConnection.

        is = inputConn.openInputStream();

Retrieve the stream data and store it in a byte array.

        byte[] data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
        result = new String(data);

Catch any errors that might be generated by your procedure.

    catch(Exception e)
    {
        result = "ERROR fetching content: " + e.toString();
    }

Close your OutputStream.

        if(os != null)
        {
            try
            {
                os.close();
            }
            catch(IOException e)
            {
                // process the error condition
            }
        }

Close your InputStream.

        if(is != null)
        {
            try
            {
                is.close();
            }
            catch(IOException e)
            {
            }
        }

Close your Connection.

        {
            connection.close();
        }
        catch(IOException ioe)
        {
        }
    }

Call showContents() that you created in step 6.

    showContents(result);
}
}

Code sample: Retrieving a web page using the GCF

This code sample uses the BlackBerry Mobile Data System transport. To make this code sample as generic as possible, the InputConnection and OutputConnection interfaces are used in place of the HttpConnection interface.

import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.UiApplication;
import java.io.*;
import javax.microedition.io.*;


public class NetworkSample extends UiApplication 
{
    public static void main(String[] args) 
    {
        NetworkSample app = new NetworkSample();
        app.enterEventDispatcher();
    }
    public NetworkSample() {
        new HTTPConnectionSetup();
    }
}

class HTTPConnectionSetup 
{

    public HTTPConnectionSetup()
    {

        Thread t = new Thread(new Runnable()
        {

            public void run() {
                Connection c = null;
                try 
                {
                    c = Connector.open("http://www.blackberry.com;deviceside=false");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(c != null)
                {
                    displayContent(c);
                }
            }

        });
        t.start();
    }

    private void displayContent(final Connection c) {
        // When the connection thread completes, show the data from the web server
        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
            public void run() {
                UiApplication.getUiApplication().pushScreen(new HTTPOutputScreen(c));
            }
        });
    }

}

class HTTPOutputScreen extends MainScreen 
{

    RichTextField _rtfOutput = new RichTextField();

    public HTTPOutputScreen(Connection conn)
    {
        // Create a container for the data, and put it on the screen.
        _rtfOutput.setText("Retrieving data. Please wait...");
        add(_rtfOutput);
        // Retrieve the data from the web server, using the connection, on a 
        // separate thread.
        ContentReaderThread t = new ContentReaderThread(conn);
        t.start();
    }

    // After the data has been retrieved, display it.
    public void showContents(final String result) 
    {
        UiApplication.getUiApplication().invokeLater(new Runnable() 
        {

            public void run() 
            {
                _rtfOutput.setText(result);
            }
        });
    }

    private final class ContentReaderThread extends Thread
    {
        private Connection _connection;

        ContentReaderThread(Connection conn)
        {
            _connection = conn;
        }

        public void run()
        {
            String result = "";
            OutputStream os = null;
            InputStream is = null;

            try
            {
                // Send HTTP GET to the server.
                OutputConnection outputConn = (OutputConnection) _connection;
                os = outputConn.openOutputStream();
                String getCommand = "GET " + "/" + " HTTP/1.0\r\n\r\n";
                os.write(getCommand.getBytes());
                os.flush();

                // Get InputConnection and read the server's response.
                InputConnection inputConn = (InputConnection) _connection;
                is = inputConn.openInputStream();
                byte[] data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
                result = new String(data);
                // is.close();

            }
            catch(Exception e)
            {
                result = "ERROR fetching content: " + e.toString();
            }
            finally
            {
                // Close OutputStream.
                if(os != null)
                {
                    try
                    {
                        os.close();
                    }
                    catch(IOException e)
                    {
                    }
                }

                // Close InputStream.
                if(is != null)
                {
                    try
                    {
                        is.close();
                    }
                    catch(IOException e)
                    {
                    }
                }

                // Close Connection.
                try
                {
                    _connection.close();
                }
                catch(IOException ioe)
                {
                }
            }

            // Show the response received from the web server, or an error message.
            showContents(result);
        }
    }


}

Using the BlackBerry Enterprise Server as a network gateway

When you use the BlackBerry Enterprise Server as a network gateway, all traffic between your app and the BlackBerry Enterprise Server is encrypted using AES or triple DES encryption. Because the BlackBerry Enterprise Server is located behind the organization's firewall and provides inherent data encryption, apps can communicate with application servers and web servers that are located on the organization's intranet. The BlackBerry Mobile Data System component of the BlackBerry Enterprise Server includes BlackBerry MDS Services, which provides an HTTP and TCP/IP proxy service to allow the BlackBerry Java Application to use it as a secure gateway for managing HTTP and TCP/IP connections to the intranet.

If your app connects to the Internet, you might be able to use the BlackBerry Enterprise Server as a gateway. Network requests travel behind the organization's firewall to the BlackBerry Enterprise Server, which makes the network request to the Internet through the corporate firewall. Administrators can set an IT policy to make sure that the BlackBerry Enterprise Server is the gateway for all wireless network traffic, including traffic destined for the Internet.

If your app connects to the Internet, you can also use either the BlackBerry Internet Service or the Internet gateway of the wireless service provider to manage connections.

Using a wireless service provider's Internet gateway

Most wireless service providers provide an Internet gateway that offers direct TCP/IP connectivity to the Internet. Some wireless service providers also provide a WAP gateway that allows HTTP connections to use the WAP protocol. A BlackBerry Java Application can use either of these gateways to connect to the Internet. If your app is for BlackBerry smartphone users who are on a specific wireless network, using the wireless service provider's Internet gateway can often yield fast, and reliable connections. If your app is for users on a variety of wireless networks, testing your app against the different Internet gateways can be challenging. In this case, you should use the BlackBerry Internet Service transport, and use the wireless service provider’s Internet gateway as a backup connection type if the BlackBerry Internet Service transport is not available.