Java Reference
In-Depth Information
112.
catch (Exception ex)
113.
{
114.
System.out.println("Problem in GO!: URL not found.");
115.
}
116.
}// ifelse
117.
}// method
118.
}// internal class
119.
}
22.4
Reading a web page
In the previous section we saw how HTML pages can displayed in a formatted way.
Now we show how the source code of a web page can be read. This is useful if the
application has to read and process information from the page. An example for
extracting information from the web is given in the next section.
Our non-graphical program ReadURL accesses a web page and writes its source
code to the console. We use one of the test pages for this topic, namely:
http://www.imm.dtu.dk/swingbook/HTMLTest/test1.html
In our application we create a URL -object with this address. Then an InputStream
for reading from that URL is created. This is done by using method openStream()
of class URL .Wethen use method read() of class InputStream to read the source
of the HTML page character by character. Each character is immediately written
to the console. The code of ReadURL and the resulting console output are listed
below.
File: its/OnlineMonitor/ReadURL.java
1.
package its.OnlineMonitor;
2.
3.
import java.io.InputStream;
4.
import java.net.URL;
5.
6.
public class ReadURL {
7.
8.
private static String immURL =
"http://www.imm.dtu.dk/swingbook/HTMLTest/test1.html";
9.
10.
public static void main(String[] args) {
readAndPrintTheURL(immURL);
11.
}
12.
13.
14.
public static void readAndPrintTheURL(String urlName){
// Create a URL
15.
Search WWH ::




Custom Search