Java Reference
In-Depth Information
Listing 12-1. Opening an HTTP Connection and Obtaining an InputStream
String url = "http://www.nowhere.com";
StreamConnection c = null;
InputStream s = null;
try {
c = (StreamConnection)Connector.open(url);
s = c.openInputStream();
} catch (ConnectionNotFoundException e) {...}
catch (IllegalArgumentException e) {...}
catch (IOException ioe) {...}
finally {
try {
if (s != null) s.close();
if (c != null) c.close();
} catch (Exception e) {...}
}
This pseudocode is fairly typical for most applications that use connections. You
begin by constructing a URL describing where the connection should be made, and then
you use Connection.open to generate a concrete Connection class that implements the con-
nection to the address you specified in the URL. Once the connection is open, you obtain
streams (or datagrams) from the connection and perform your I/O using the provided
streams or datagrams. When you're finished, you need to close both the stream (not the
datagram connections) and the connection itself.
Programming with connections is fraught with exceptions, because you're at the
mercy of the outside environment. A network might not be available, a handset might
not have service, or sufficient resources may not be available on the device to accommo-
date your network request. Consequently, open can throw a number of exceptions:
ConnectionNotFoundException : If the platform doesn't support the requested
protocol, or if the platform cannot find the target specified by the URL
IllegalArgumentException : If you specify an invalid parameter
IOException : If any kind of I/O error occurs while opening the connection
SecurityException : If your application is not permitted to access the protocol
you request
 
Search WWH ::




Custom Search