Send and receive data using a network connection

The following task 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.
Before you begin: Open a network connection and pass a Connection object to the constructor of the class that is developed in this task. For more information about opening network connections, see Open a network connection using the Network API or Open a network connection using the GCF.
  1. 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.*;
  2. Create a class that extends the MainScreen class.
    public class HTTPOutputScreen extends MainScreen 
    {
  3. Create an instance variable for a RichTextField object to display the results.
    RichTextField _rtfOutput = new RichTextField();
  4. Create a constructor that accepts a Connection object as an argument.
    public HTTPOutputScreen(Connection conn)
    {
  5. 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();
  6. Create a method to populate your RichTextField with the data that is returned from the web site, after ContentReaderThread completes. You invoke this method in step 20.
    public void showContents(final String result) 
    {
        UiApplication.getUiApplication().invokeLater(new Runnable() {
    
            public void run() {
                _rtfOutput.setText(result);
            }
        });
    }
    
  7. 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()
        {
    
  8. Initialize an OutputStream object and an InputStream object to exchange data with the web site.
        OutputStream os = null;
        InputStream is = null;
  9. Initialize a String object to store the response from the web site.
        String result = "";
  10. Create an OutputConnection object to send data over your connection.
        try
        {
            OutputConnection outputConn = (OutputConnection) connection;
  11. 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();
  12. 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();
  13. Create an InputConnection object to receive data from your connection.
            InputConnection inputConn = (InputConnection) connection;
  14. Retrieve an InputStream from your InputConnection.
            is = inputConn.openInputStream();
  15. 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);
  16. Catch any errors that might be generated by your procedure.
        catch(Exception e)
        {
            result = "ERROR fetching content: " + e.toString();
        }
  17. Close your OutputStream.
            if(os != null)
            {
                try
                {
                    os.close();
                }
                catch(IOException e)
                {
                    // process the error condition
                }
            }
  18. Close your InputStream.
            if(is != null)
            {
                try
                {
                    is.close();
                }
                catch(IOException e)
                {
                }
            }
  19. Close your Connection.
            {
                connection.close();
            }
            catch(IOException ioe)
            {
            }
        }
  20. Call showContents() that you created in step 6.
        showContents(result);
    }
    }

Was this information helpful? Send us your comments.