Java Reference
In-Depth Information
for using a ContentConnection and InputStream to read the results from the server, closing the
streams and connection when the code finishes reading from the stream.
Putting HTTP to Work
Using the GCF for connections to remote resources is simple in theory, but in practice it's
a little more complex, for two reasons. First, and most importantly, you must handle all of
the exceptions that may arise; the pseudocode you've seen before indicates that excep-
tions can occur, but the pseudocode doesn't do anything useful with them. Second, you
want to perform your I/O on a separate thread, because the connections usually block
the thread on which they operate while they exchange data with the remote server. While
on some devices and networks, this delay can be negligible, there's no guarantee of this,
and the result of having connections perform their work on the main thread is a frozen
user interface—something intolerable for users.
Listing 12-10 shows the WeatherFetcher class, which uses HTTP to obtain the weather
forecast for a specific city and state. The WeatherWidget example uses it to obtain
weather forecasts from a remote web server, as you see in Listing 12-11. (If you're follow-
ing along with the listings in this chapter, you will want to make the changes in all of the
listings in your project, because they are interrelated.)
â– 
Note The implementation of WeatherFetcher assumes that the remote web server can provide weather
forecasts given a city and state, and that the resulting weather forecasts are provided to the application in
plain text. In the next chapter, I build on what you learn here to see how an actual web service would use
XML to provide structure to the request and response data.
Listing 12-10. The WeatherFetcher Class
package com.apress.rischpater.weatherwidget;
import java.io.*;
import javax.microedition.io.*;
public class WeatherFetcher implements Runnable {
private String url = "http://www.noplace.com/weather";
private Thread thread;
private Location location;
private boolean cancelled;
WeatherWidget app;
 
Search WWH ::




Custom Search