Java Reference
In-Depth Information
String headerKey = null;
while((headerKey = conn.getHeaderFieldKey(i++)) != null)
{
midlet.append(headerKey,conn.getHeaderField(headerKey));
}
An
HttpConnection
is opened using the URI given by the user and
is used first to retrieve the HTTP response code (200, in case of success).
We also loop through the HTTP response methods until they are all read
and append them to the MIDlet's
Form
object as a
StringItem
.
Having read the HTTP readers, it is time to read the actual HTML
content. We open an
InputStream
from the
HttpConnection
,start
reading the input and save it to a
StringBuffer
of TEXT FIELD SIZE
length. Once we reach this value in number of bytes read, we leave the
loop, as we don't want to pollute the user's screen with too much raw
HTML.
InputStream in = conn.openInputStream();
StringBuffer buffer = new StringBuffer(TEXT_FIELD_SIZE);
int ch;
int read = 0;
while ( (ch = in.read()) != -1 && read < TEXT_FIELD_SIZE)
{
buffer.append((char)ch);
read++;
}
After reading TEXT FIELD SIZE bytes of HTML, we append them to the
MIDlet's
Form
so they can be shown on the screen along with all the
other information we retrieved. Figure 2.18 shows the
NetworkDemo
MIDlet running on a Nokia N95. The full source code, JAD and JAR
files for the
NetworkDemo
MIDlet are available for download from this
topic's website.
(a)
Figure 2.18
NetworkDemo
MIDlet running on a Nokia N95: a) connecting to the URL,
b) receiving the headers, and c) reading the HTML
(b)
(c)