Java Reference
In-Depth Information
■
Tip
If you're passing name-value pairs using the HTTP
GET
or
POST
methods, it's imperative that you
URL-encode the values, or else the URL will be malformed and the responding server likely will not process
your result. The full syntax for URL encoding is described in RFC 2396.
Once the outgoing data is URL-encoded, it's time for
run
to set up the HTTP connec-
tion. It does this using the GCF, setting the request method to
POST
, indicating that the
content type being sent is URL-encoded form data as if from a web browser, and specifying
the length of the data. (This example
could
have used an HTTP
GET
request and simply
tacked the form data on the end of the URL, but it's more useful to show you how to make
an HTTP
POST
request, because it's likely you'll be using
POST
for any serious web service
interactions anyway.)
With the connection configured, the code writes the arguments to the connection's
output stream and proceeds to open and read the result from the input stream. In prac-
tice, this is where the code is likely to block; on a mobile wireless device, it may take up to
a second or so for this interaction to proceed. In fact, it's quite likely that this transaction
will take
longer
to process this interaction, at least the first time the application executes,
because many devices, especially MIDP devices, will ask the user to permit the MIDlet if
it's OK to perform the request. Only signed third-party applications are permitted to use
network resources without permission; others will prompt the user for permission prior
to initiating any network request.
Once the code reads the result from the network, it constructs a new
String
with the
resulting data and updates the
Location
object with the new data before notifying the
application that the
Location
object has changed.
■
Tip
In a crude sense, the
WeatherFetcher
is using the Observer pattern, using the
Location
object it
received at initialization as a model, and the application as a receiver of updates. I could have constructed a
more elaborate interface and class hierarchy to represent this, although doing so would not have simplified
the purpose of this example, which is to show you how to use the
HttpConnection
.
The static
urlEncode
method is trivial, creating a new string based on an input string.
The new string has URL-encoded characters for any nonalphabetic characters. Frankly,
it's a mystery to me why the CLDC and CDC don't provide this function somewhere as a
utility; most network-aware applications are going to need it anyway.
Integrating the
WeatherFetcher
class into the WeatherWidget application does not
require much work; starting from the implementation you last saw in Chapter 6, you only
need to make a few changes to the MIDlet itself to initiate requests for weather updates
when the MIDlet first launches or when you select a new location from the location list.
Listing 12-11 shows these changes.