Uniform Resource Locator: URL Hierarchy of Classes Methods of the Class Examples of Using the Class
Hierarchy of Classes
URL Class Class URL is a description of a resource location on the Internet. Complete URL: http://www.cs.joensuu.fi:1547/~john/pub/index.html -- protocol : http:// -- host : www.cs.joensuu.fi -- port : 1547 -- path : ~smith/pub/index.html Java provides a class—java.net.URL—to manipulate URLs.
Methods of URL Class Main methods of the class URL: URL(String url): create an object using the string parameter (exception MalformedURLException). URL(String, String, String): protocol, host, path of the resource. String toString(): return the URL as a strings. String getHost(): return the name of the host linked to this URL. String getProtocol(): return le protocol of this URL. String getPort(): return the number of the associate port.
Methods of URL Class InputStream openStream(): realize the connection to the URL previously instantiated. An InputStream object is returned and permits to retrieve information specified into the URL. If the connection fails, the exception IOException is raised.
Creating a URL Instance The following statement creates a Java URL object: String str = "http://www.sun.com”; try { URL location = new URL(str); } catch(MalformedURLException ex) { }
Example 18.6: Retrieving Remote Files Rather than reading the file from the local system, this example reads the file from a Web server. private void showFile() { URL url = null; try { url = new URL(urlString); InputStream is = url.openStream(); infile = new BufferedReader( new InputStreamReader(is)); } catch (FileNotFoundException e) { ... } catch (IOException e) { ... }
Viewing HTML Pages Given the URL of the page, a Web browser can view an HTML page—for example, http://www.sun.com. HTTP (Hypertext Transfer Protocol) is the common standard used for communication between a Web server and the Internet. You can open a URL and view a Web page in a Java applet.
Example 18.5 Viewing HTML Pages from Java The following figure shows the process by which an applet/application reads the files on the Web server:
Example 18.5 Viewing HTML Pages from Java The following figure shows the process by which an applet/application reads the files on the Web server: