18. The Generic Connection Framework

ALL network access in MIDP devices works through the Generic Connection Framework (GCF), a simple API that makes quick work of many types of communication. The fundamental idea of GCF is very simple. Your application supplies a connection string, and GCF hands back the corresponding input and output streams.

The MIDP 2.0 specification says that devices must support HyperText Transfer Protocol (HTTP) and secure HTTP (HTTPS) connections, which means your application has two powerful guarantees for connectivity to the awesome power of the Internet.

This chapter describes the simple premise of GCF and provides details on HTTP and HTTPS networking. It also provides some details on optional connection types. Later chapters cover the details of SMS, MMS, Bluetooth, and other network connections.

18.1. Making Connections

GCF is contained in javax.microedition.io. The Connector class runs the show, and a hierarchy of Connection interfaces represent different connection types.

To use GCF, pass a connection string to one of Connector’s open() methods. It hands you back some Connection implementation that you can use to get input and output streams. Connection strings are URLs with a protocol, network address, and optional parameters.

Here is an example that attempts an HTTP connection.

Image

The object returned from Connector’s open() method is an implementation of Connection. Connection isn’t useful by itself, so you must cast the return value to a more specific connection type before you can do anything with it. GCF defines many Connection subinterfaces to support serial ports, sockets, datagrams, HTTP, HTTPS, and even server sockets. Optional APIs add even more connection types. JSR 205 defines MessageConnection to support SMS and MMS, JSR 82 defines L2CAPConnection for Bluetooth, and so forth. GCF is so general that it is also used for purposes that are not, strictly speaking, network connections, like the FileConnection you learned about in Chapter 15.

Figure 18.1 shows a diagram of the path from Connection to HttpConnection and the methods defined along the way. It is not a complete diagram of the Connection family.

Figure 18.1. Part of Connection’s family tree

Image

If you wanted to load the contents of an image file, you could do something like this:

Image

In this case, you are using the openInputStream() method that HttpConnection inherits from InputConnection.

Once you’ve got a stream or two, the rest of your code should be standard java.io programming. GCF, then, provides your application with a way to get streams that connect to interesting things, like Web servers or serial ports or Bluetooth devices.

18.2. Clean Up

Like any other resource, network connections should be closed when you are finished with them. The base Connection interface defines a close() method for this very purpose. It is also a good idea to close any of the Connection’s streams independently. Finally, good practice dictates that all this closing take place in a finally block, just to make sure it gets executed. It is a little messy, but it is the safest way to go. Here is a skeleton of a method that reads data from an HTTP network connection and cleans up properly.

Image

The method that calls loadBytes() should catch and handle IOException and SecurityException.

18.3. Use Threads

Network access can take a long time. A typical HTTP connection is subject to the relatively slow speed of today’s wireless networks, the whims of the Internet, the speed of the server, the overhead of HTTP connections, and many other factors.

Back in Chapter 4, I told you that you should use a separate thread for any operation that you expect will take a long time. Network access is one of those lengthy operations.

The threading in the examples in this chapter is very simple. Each new network connection is performed in a newly created thread. For more complex applications, a dedicated network thread is more appropriate. You can queue up network requests and let the network thread handle them one at a time. This means you are using only one extra thread and one network connection at a time. This is a good idea on small devices that have limited resources for multiple threads and multiple network connections.

Don’t forget about your users, either. They are impatient and needy. They are trying to get something done and network access is slowing them down. Put up a pretty wait screen or an amusing animation. If possible, allow them to keep working while your application hits the network in the background.

18.4. Image Loading via HTTP

Here is an example that loads a small image from a Web server and displays it in a form. The form is created in startApp() with a continuous indefinite gauge, which provides an animation to keep the user enthralled while the image is loading. startApp() also kicks off a thread to do the network access.

The connection is set up in run(), while the actual image data is read using the readAll() method originally presented in Chapter 4.

Image

Image

Image

The image URL is hardcoded here, but you can override it to try a different image by changing the application property image-url. The hardcoded URL produces the results shown in Figure 18.2.

Figure 18.2. The image has been loaded via HTTP.

Image

18.5. Advanced HTTP Techniques

The HttpConnection interface has lots of methods. In theory, you can use these methods to do some fancy stuff:

  • You can perform HTTP POSTs from a MIDlet. The default connection type is GET, but a call to setRequestMethod(HttpConnection.POST) makes the change. Unfortunately, you’ll have to do your own parameter encoding. Stick with GET if possible.

  • Some Web applications use HTTP cookies for session tracking or other purposes. It’s possible to create a cookie-aware MIDlet. You can retrieve cookies sent by the server by calling getHeaderField(“Set-cookie”) on an HttpConnection. Next time you open an HttpConnection, pass the cookie value by calling setRequestProperty(“cookie”, value).

  • HttpConnection provides access to all of the headers sent in the request and received in the server response. You should be able to perform the same kind of HTTP processing that you would be able to do on any other platform.

Before you get all fired up about this fancy HTTP stuff, though, be aware that HTTP headers might get mangled between your server and your users’ devices. Read on for more details.

18.6. Tips for Success

Making HTTP connections consistently across a wide variety of devices is surprisingly difficult for two main reasons:

  • Different devices have different implementation behavior and bugs.

  • Various gateways lie between your device and the Internet. These gateways sometimes meddle with your requests and responses.

The best way to understand the quirks of particular devices and how to code defensively is to talk with other developers who have already had the pain of discovering the idiosyncrasies of real devices. One enlightening thread on the subject of HTTP connections is here:

http://archives.java.sun.com/cgi-bin/wa?A2=ind0511&L=kvm-interest&P=R2451&I=-3

To protect yourself from meddlesome gateways, don’t try to do anything tricky with your HTTP requests and responses. Gateways might modify or remove anything that they don’t recognize.

  • Don’t rely on sending custom headers.

  • Don’t rely on custom HTTP response messages.

  • Don’t try to send a response body with anything but 200 OK.

  • Don’t rely on cookies.

18.7. Using HTTPS

HTTPS is HTTP run on a secure socket connection, typically Transport Layer Security (TLS) or Secure Sockets Layer (SSL). This means that the HTTP requests and responses that pass between the device and the server are encrypted.

HTTPS is powerful and can be complex, but fortunately it’s very easy to use in a MIDlet. Most of the time, you can simply use HttpsConnection in place of HttpConnection, and use the corresponding HTTPS connection string:

Image

HttpsConnection descends from HttpConnection, which means you already know how to use it. If you want more information about the HTTPS connection, HttpsConnection defines two additional methods, including one that returns a SecurityInfo object.

Here is an example that shows information about an HTTPS connection.

Image

Image

Image

On Sun’s emulator, shown in Figure 18.3, you get quite a bit of information.

Figure 18.3. Information about an HTTPS connection

Image

Most of the time, an HTTPS connection will be sufficient to hide your users’ data from prying eyes. If you would like a more detailed story, read this article:

http://developers.sun.com/techtopics/mobility/midp/articles/security2/

18.8. Other Connection Types

MIDP requires support for HTTP and HTTPS connections, but it also defines connection strings and Connection subinterfaces for other connection types. The exact format for the connection strings is defined in the API documentation for the corresponding connection interface.

Although socket connections are widely supported, the others are not. None of these connections types are required to be supported, so proceed with caution.

Image

SocketConnection is for IP sockets. Just specify a host and port number. SecureConnection works the same way but uses SSL or TLS to make an encrypted connection.

DatagramConnection is a little different. You create the connection by specifying a host and port number, but you don’t use streams to write and read data. Instead, use one of the newDatagram() methods in DatagramConnection to create a new Datagram object. Populate the Datagram, then send it out with send(). In a separate thread, you can call receive(), which blocks until a datagram is received.

CommConnection represents a serial port on the device. The serial port could be a physical port or a virtual one like an infrared port. You can specify various connection parameters in the connection string, like data rate, parity, and so forth. Take a look at the CommConnection API documentation for all the details.

You can get a list of all the available serial ports on a device by retrieving the system property microedition.commports. The return value (if it is not null) is a comma-separated list of port names.

The following example shows how to parse the serial port names (see getCommPorts()) and attempts to open input and output streams on each named port.

Image

Image

Image

18.9. Incoming Connections

Certain connection strings correspond to incoming connections. You already caught a glimpse of this in Chapter 6 when you learned about the push registry.

To set up a server socket, for example, use a socket connection string with no host, like this:

Image

Pass this connection string to Connector.open() to receive a ServerSocketConnection for port 2051. The acceptAndOpen() waits for an incoming socket connection and returns it as a StreamConnection. Assuming you have devices and a wireless network that support socket connections, you could use a ServerSocketConnection to set up a device-to-device socket connection for a game or other application. In practice, server sockets are unlikely to be supported.

If you have a device and network that supports it, you can also set up your MIDlet to receive datagram connections. Again, you use a datagram-style connection string but omit the host:

Image

Optional APIs also define connection strings for incoming network connections. For example, the JSR 205 Wireless Messaging API (WMA) 2.0 defines connection strings for applications that wish to receive incoming SMS or MMS messages.

18.10. Connection Permissions

Making network connections is a sensitive operation from a security standpoint. HTTP and HTTPS connections might result in charges to the user, and local connections like Bluetooth or serial port connections can pose security or privacy risks.

Each connection type has a corresponding permission. For example, HTTP connections correspond to the javax.microedition.io.Connector.http permission. Don’t forget to add the right permissions to your MIDlet suite’s descriptor as required permissions or optional permissions.

If you cryptographically sign your application, it is likely to be placed into a security domain where network access is allowed or where the device will ask the user for permission only once at installation time. Leave your application unsigned and your users will probably have to work through a lot of security prompts.

18.11. Summary

The Generic Connection Framework (GCF) allows applications to trade connection strings for input and output streams. Network access should be performed in application threads, and applications should be scrupulous about closing open connections. HTTP and HTTPS must be available, and socket, datagram, serial, and other connection types might also be available via GCF. Server socket and datagram listener connections are also possible. Applications must have appropriate permissions to make network connections.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.239.166