Java Reference
In-Depth Information
Figure 12-37 displays lines 439 through 467 of the WebStocks servlet code.
The getQuote() method beginning in line 439 requires a stock symbol as a
parameter and then, in lines 449 through 451, creates a new URL object using
the address of the Yahoo! stock quote Web service and the necessary parameters
to obtain a quote for the stock symbol. In general, creating a connection to a
URL is a multistep process: a connection object is created for a remote object
specified by a URL; setup parameters and request properties are manipulated,
if necessary; the actual connection is made; and the remote object at that URL
becomes available for access. Line 453 calls the openConnection() method of
the URL to create a connection object. No additional setup parameters need
manipulation, so line 454 calls the connect() method to make the actual
connection. Lines 455 and 456 get the input stream of data from the connected
URL and wrap the input stream with a buffered reader in order to read the
data one line at a time. Recall that wrapping a BufferedReader around an
InputStreamReader buffers the input to make reading the data more efficient.
Lines 458 and 459 read each line of data and append it to a StringBuffer. A new-
line character is inserted after each line because the BufferedReader readLine()
method removes the end of line character from the data stream.
FIGURE 12-37
Because the URL class constructor throws an exception if the URL is formed
improperly, the exception is caught and a message is displayed on the console
(lines 461 through 464). Because the URL does not change, this error never
should occur; however, the exception must be either caught or thrown. If an
invalid stock symbol is entered, the Web service returns a result indicating fields
not applicable for the stock.
Search WWH ::




Custom Search