Home > Articles > Programming > Java

Like this article? We recommend

The Generic Connection Framework

The Generic Connection framework is introduced in J2ME's CLDC to reflect the requirements of small-footprint networking and file I/O for a broad range of mobile devices.

To meet the small-footprint requirement, the Generic Connection framework generalizes the functionality of J2SE's network and file I/O classes from J2SE's java.io and jave.net packages. It is a precise functional subset of J2SE classes, but much smaller in size. These J2ME classes and interfaces are all included in a single package, javax.microedition.io.

To meet the extendibility and flexibility requirement, the Generic Connection framework uses a set of related abstractions for different forms of communications, represented by seven connection interfaces: Connection, ContentConnection, DatagramConnection, InputConnection, OutputConnection, StreamConnection, and StreamConnectionNotifier.

The Generic Connection framework supports the following basic forms of communications. All the connections are created by one common method, Connector.open():







Serial Port:




This flexible design makes adding a new form of communication much easier without causing major structural changes to the class libraries.

Figure 9.1 shows the hierarchical relationships between these connection interfaces.

Connection Interfaces

As shown in Figure 9.1, Connection is the base interface, the root of the connection interface hierarchy. All the other connection interfaces derive from Connection. StreamConnection derives from InputConnection and OutputConnection. It defines both the input and output capabilities for a stream connection. ContentConnection derives from StreamConnection. It adds three methods for MIME data handling to the input and output methods in StreamConnection. Finally, HttpConnection derives from ContentConnection.

The HttpConnection is not part of the Generic Connection framework. Instead, it is defined in the MIDP specification that is targeted at cellular phones and two-way pagers. HttpConnection contains methods and constants specifically to support the HTTP 1.1 protocol. The HttpConnection interface must be implemented by all MIDP implementations, which means the HttpConnection will be a concrete class in the actual MIDP implementations. The http communication capability is expected to be available on all MIDP devices.

Figure 9.1 The connection interface hierarchy.

Why are these connections defined as interfaces instead of concrete classes? Because the Generic Connection framework specifies only the basic framework of how these connection interfaces should be implemented. The actual implementations are left to individual device manufacturers' profile implementations (MIDP or PDAP). As discussed in the previous section, individual device manufacturers may be interested in implementing only a subset of these connection interfaces based on the capabilities of their devices. The documentation of each manufacturer's J2ME MIDP SDK should indicate which connection interfaces are implemented and which are not.

Creating Network Connections

So far we have talked about the different kinds of connections. You may wonder how the connections are created and how to use them.

The Connector class is the core of the Generic Connection framework, because all connections are created by the static open() method in the Connector class. Different types of communication are created from the same method. The connection type can be file I/O, serial port communication, datagram connection, or an HTTP connection, depending on the string parameter passed to the method. Such a design makes the J2ME implementation more extensible and flexible in supporting new devices and product.

The method's signature is as follows:

Connection open(String connect_string)

The connect_string has a format of {protocol}:[{target}][{params}], which is similar to the commonly used URL format, such as http://www.somewhere.com. It consists of three parts: protocol, target, and params.

protocol dictates what type of connection will be created by the open() method. There are several possible values for protocol, as listed in Table 9.1.

Table 9.1 Protocol Values


Connection Usage


File I/O


Serial port communication


TCP/IP socket communication


Datagram communication


Accessing Web servers

target can be a hostname, a network port number, a file name, or a communication port number.

params is optional. It specifies the additional information needed to complete the connect string.

The following examples demonstrate how to use the open() method to create different types of communication based on different protocols:

HTTP communication:

Connection hc = Connector.open("http://www.webyu.com")

Socket communication:

Connection sc = Connector.open("socket://localhost:9000")

Datagram communication:

Connection dc = Connector.open("datagram://http://www.webyu.com:9000")

Serial port communication:

Connection cc = Connector.open("comm:0;baudrate=9000")

File I/O:

Connection fc = Connector.open("file:/foo.dat")


Actual support for these protocols varies from vendor to vendor. Of all the J2ME MIDP implementations we have evaluated (Sun's J2ME Wireless Toolkit, MotoSDK from Motorola, and RIMSDK from Research in Motion), MotoSDK supports all three networking protocols that we are concerned with in this chapter: socket (TCP/IP), datagram (UDP), and http (HTTP). For this reason, all the sample codes in this chapter are compiled and run under MotoSDK (release 0.7).

A ConnectionNotFoundException will be thrown if your MIDlet program tries to create a connection based on a protocol that is not supported by your device manufacturer's MIDP implementation.

Even though we said that Sun's J2ME Wireless Toolkit only supports the http communication, there is actually an undocumented feature that will let you run socket or datagram programs under the Toolkit if you set the environment variable ENABLE_CLDC_PROTOCOLS=INTUITIVE_TOOLKIT. Because it is an undocumented feature that is not officially supported by Sun, we chose not to use Sun's J2ME Wireless Toolkit to run our samples in this chapter.

The Methods in the Connector Class

This section takes a close look at the Connector class. The Connector class is the only concrete class in Generic Connection framework in CLDC. It contains seven static methods:

static Connection open(String connectString)

This method creates and opens a new Connection based on the connectString.

static Connection open(String connectString, int mode)

This method creates and opens a new Connection based on the connectString. The additional mode parameter specifies the access mode for the connection. There are three access modes: Connector.READ, Connector.READ_WRITE, and Connector.WRITE. If mode is not specified, the default value is Connector.READ_WRITE. The validity of the actual setting is protocol dependent. If the access mode is not allowed for a protocol, an IllegalArgumentException will be thrown.

static Connection open(String connectString, int mode, boolean timeouts)

This method creates and opens a new Connection based on the connectString. The additional timeouts parameter is a Boolean flag that dictates whether the method will throw a timeout exception InterruptedIOException. The default timeouts value is false, which indicates that no exception will be thrown.

static DataInputStream openDataInputStream(String connectString)

This method creates and opens a new DataInputStream based on the connectString.

static DataOutputStream openDataOutputStream(String connectString)

This method creates and opens a DataOutputStream from the connectString.

static InputStream openInputStream(String connectString)

This method creates and opens a new InputStream from the connectString.

static OutputStream openOutputStream(String connectString)
This method creates and opens a new OutputStream from the connectString.

The last four I/O stream-creation methods combine creating the connection and opening the input/output stream into one step. For example, the following statement

DataInputStream dis = Connector.openDataInputStream(http://www.webyu.com);

is the equivalent of the following two statements:

InputConnection ic = (InputConnection) 
 Connector.open("http://www.webyu.com", Connector.READ, false);
DataInputStream dis = ic.openDataInputStream();

An IllegalArgumentException will be thrown if a malformed connectString is received. A ConnectionNotFoundException will be thrown if the protocol specified in connectString is not supported. An IOException will be thrown for other types of I/O errors.

Listing 9.1 contains an example of how an http connection is created and how a DataInputStream is opened on top of the connection.

Listing 9.1 Listing1.txt

 * This sample code block demonstrates how to open an 
 * http connection, how to establish an InputStream from
 * this http connection, and how to free them up after use.

// include the networking class libraries
import javax.microedition.io.*;
// include the I/O class libraries
import java.io.*;

// more code here ...

// define the connect string with protocol: http
// and hostname:
String connectString = "";
InputConnection hc = null;
DataInputStream dis = null;

// IOException must be caught when Connector.open() is called
try {
  // an http connection is established with read access.
  // The returned object is cast into an InputConnection object.
  hc = (InputConnection) 
   Connector.open(connectString, Connector.READ, false);
  // an InputStream is created on top of the InputConnection
  // object for read operations.
  dis = hc.openDataInputStream();
  // perform read operations here ...
} catch (IOException e) {
  System.err.println("IOException:" + e);
} finally {
  // free up the I/O stream after use
  try { if (dis != null ) dis.close(); }
  catch (IOException ignored) {}
  // free up the connection after use
  try { if ( hc != null ) hc.close(); }
  catch (IOException ignored) {}

// more code here ...

Connection Interfaces

This section takes a look at all the connection interfaces defined in the javax.microedition.io package including the seven connections from the Generic Connection framework in CLDC and the HttpConnection in MIDP:



The Connection interface has one method:

void close()

This method closes the connection.



The InputConnection interface has two methods:

DataInputStream openDataInputStream()

This method opens a data input stream from the connection.

InputStream openInputStream()

This method opens an input stream from the connection.



The OutputConnection interface has two methods:

DataOutputStream openDataOutputStream()

This method opens a data output stream from the connection.

OutputStream openOutputStream()

This method opens an output stream from the connection.



The DatagramConnection interface is used to create a datagram for a UDP communication. More details regarding this interface are discussed in the section "Wireless Network Programming Using Datagrams." This interface has eight methods:

int getMaximumLength()

This method returns the maximum length that is allowed for a datagram packet.

int getNominalLength()

This method returns the nominal length for datagram packets.

Datagram newDatagram(byte[] buf, int size)

This method creates a new Datagram object. buf is the placeholder for the data packet, and size is the length of the buffer to be allocated for the Datagram object.

Datagram newDatagram(byte[] buf, int size, String addr)

This method creates a new Datagram object. The additional parameter addr specifies the destination of this datagram message. It is in the format {protocol}://[{host}]:{port}.

Datagram newDatagram(int size)

This method creates a new Datagram object with an automatically allocated buffer with length size.

Datagram newDatagram(int size, String addr)

This method creates a new Datagram object. addr specifies the destination of this datagram message.

void receive(Datagram dgram)

This method receives a Datagram object dgram from the remote host.

void send(Datagram dgram)

This method sends a Datagram object dgram to the remote host.



The StreamConnection interface offers both send and receive capabilities for socket-based communication. All four of its methods are inherited from InputConnection and OutputConnection:

DataInputStream openDataInputStream()
InputStream openInputStream()
DataOutputStream openDataOutputStream()
OutputStream openOutputStream()


The StreamConnectionNotifier interface has one method:

StreamConnection acceptAndOpen()

This method returns a StreamConnection that represents a server-side socket connection to communicate with a client.



The ContentConnection interface extends from StreamConnection and adds three methods to determine an HTTP stream's character encoding, MIME type, and size:

String getEncoding()

This method returns the value of the content-encoding in the HTTP header of an HTTP stream.

long getLength()

This method returns the value of the content-length in the HTTP header of an HTTP stream.

String getType()

This method returns the value of the content-type in the HTTP header of an HTTP stream.

The methods inherited from StreamConnection are as follows:

DataInputStream openDataInputStream()
InputStream openInputStream()
DataOutputStream openDataOutputStream()
OutputStream openOutputStream()


The HttpConnection extends from ContentConnection. It adds the following methods to support the HTTP 1.1 protocol:

long getDate()
long getExpiration()
String getFile()
String getHeaderField(int index)
String getHeaderField(String name)
long getHeaderFieldDate(String name, long def)
int getHeaderFieldInt(String name, int def)
String getHeaderFieldKey(int n)
String getHost()
long getLastModified()
int getPort()
String getProtocol()
String getQuery()
String getRef()
String getRequestMethod()
String getRequestProperty(String key)
int getResponseCode()
String getResponseMessage()
String getURL()
void setRequestMethod(String method)
void setRequestProperty(String key, String value)

The HttpConnection interface is mandatory for all MIDP vendor implementations. However, the underlying support mechanisms could be different from vendor to vendor. Some vendors may support the HTTP stack on top of non-IP–based protocols such as WSP transport or TL/PDC-P, and other vendors may use HTTP over TCP/IP. To support the HTTP protocol on MIDP devices, non-IP networks may have to install gateways in order to convert HTTP requests from the wireless network format to a TCP/IP format to be able to access the Internet.

Figure 9.2 illustrates the possible implementations of HttpConnection, based on different wireless network infrastructures.

The section "Wireless Network Programming Using HttpConnection" discusses HttpConnection in detail.

Figure 9.2 Implementations of HttpConnection on different underlying transports.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020