The NewsFetcher Class
Finally, the NewsFetcher class is responsible for downloading the articles from the Web on a separate thread to maintain the responsiveness of the user interface (see
Listing 2).
Note the form of the URL field, for example:
http://localhost:8000/WirelessNews/RSS.php
On my PC, I set the Apache Web Server to listen on port 8000 because I already had IIS listening on the default port 80. However, you'll need to change the URL string to an appropriate value for your environment. Then, when uploading the PHP files to a "real" Web Server, you will have to change the URL string to a form like this:
http://www.yourwebsite.com/WirelessNews/RSS.php
The core method of NewsFetcher is
getNews, as shown below:
private void getNews() throws IOException {
InputStream is = null;
StringBuffer sb = new StringBuffer();
HttpConnection http = null;
try {
//append the channel name onto the URL
URL += "?channel=" + channelName;
//replace not allowed chars in the URL
URL = encodeURL(URL);
//establish the connection
http = (HttpConnection) Connector.open(URL);
//set the request method as GET
http.setRequestMethod(HttpConnection.GET);
//server response
if(http.getResponseCode() == HttpConnection.HTTP_OK) {
int ch;
is = http.openInputStream();
while((ch = is.read()) != -1)
sb.append((char) ch);
}
}
catch (Exception e) {
System.err.println("Error: " + e.toString());
}
finally {
if(is != null)
is.close();
if(sb != null)
news = new String(sb);
else
news = new String();
if(http != null)
http.close();
}
Vector v;
//extract titles and descriptions from the news
if(news != "") { //success
//for debug purpose only
System.out.println(news);
v = (new NewsParser(news)).parse();
midlet.showTitles(v, true, channelName);
}
else { //failure
v = new Vector();
midlet.showTitles(v, false, channelName);
}
}
This method tries to establish an HTTP connection (type HttpConnection). It first appends the request string to the URL; then it calls the
encodeURL method, which encodes the URL, replacing any characters not allowed in a URL string. The core part of the method tries to establish the actual connection with the URL, sets the request method to
GET and checks the response from the server. If the response is OK, the method passes the string returned by the response to the
showTitles method that you saw in the WirelessNews class.