URLReader.javaThe URL
object can access content from the internet.
01: import java.net.*;
02: import java.io.*;
03:
04: public class URLReader {
05: public static void main(String[] args) {
06: URL url;
07: String name;
08: int n, nlines;
09: if (args.length>0) name = args[0];
10: else name = "https://johnloomis.org";
11: if (args.length>1) nlines = Integer.parseInt(args[1]);
12: else nlines = 5;
13: System.out.println("Opening: " + name);
14: try {
15: url = new URL(name);
16: BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
17: System.out.println("\nShowing first few lines:\n");
18: String inp;
19: for (n=0; n<nlines; n++) {
20: inp = in.readLine();
21: if (inp==null) break;
22: System.out.println(inp);
23: }
24: in.close();
25: }
26: catch (MalformedURLException e) {
27: System.out.println(e);
28: }
29: catch (IOException e) {
30: System.out.println(e);
31: }
32: }
33: }
This example triggers an URL exception:
C:\prog\java_web>java URLReader www.udayton.edu Opening: www.udayton.edu java.net.MalformedURLException: no protocol: www.udayton.edu
This example works:
C:\prog\java_web>java URLReader http://www.udayton.edu 10
Opening: http://www.udayton.edu
Showing first few lines:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>University of Dayton</title>
<meta name="ROBOTS" content="INDEX,FOLLOW" />
<meta name="googlebot" content="INDEX,FOLLOW" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"
/>
<meta http-equiv="Content-Language" content="en-us" />
Here we access a Python CGI script:
C:\prog\java_web>java URLReader "https://johnloomis.org/python/tconv.py?value=45&from=F" Opening: https://johnloomis.org/python/tconv.py?value=45&from=F Showing first few lines: <html> <head><title>Temperature Conversion</title></head> <body> <p> 45.0 F equals 7.2 C </html>
Maintained by John Loomis, updated Wed Feb 20 15:40:59 2008