java.net.URL Example
In this example, we will show the range of functionality provided by thejava.net.URL class. This class represents a Uniform Resource Locator, a pointer to a “resource” on the World Wide Web.
An URL is a text string that identifies a resource, tells where to find it, and specifies a method for communicating with it or retrieving it from its source. URLs can have many forms. The most common form has four components; a networkhost or server, thename of the resource, itslocation on that host, and aprotocol by which the host should communicate:protocol://hostname/path/resource-name.
protocol is an identifier such ashttp orftp;hostname is usually an Internet host and domain name; and thepath andresource-name components form a unique path that identifies the object on that host.
Let’s code one of the most common task for which java.net.URL class is used: Read a file using thehttp protocol.
1. Example of java.net.URL class
JavaNetURLExample.java
package com.javacodegeeks.examples;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.MalformedURLException;import java.net.URL;public class JavaNetURLExample {public static void main(String[] args) {try {// Generate absolute URL// Base URL = www.gnu.orgURL url1 = new URL("http://www.gnu.org");System.out.println("URL1: " + url1.toString());// Generate URL for pages with a common baseURL url2 = new URL(url1, "licenses/gpl.txt");System.out.println("URL2: " + url2.toString());// Generate URLs from different pieces of dataURL url3 = new URL("http", "www.gnu.org", "/licenses/gpl.txt");System.out.println("URL3: " + url3.toString());URL url4 = new URL("http", "www.gnu.org", 80, "/licenses/gpl.txt");System.out.println("URL4: " + url4.toString() + "\n");// Open URL stream as an input stream and print contents to command linetry (BufferedReader in = new BufferedReader(new InputStreamReader(url4.openStream()))) {String inputLine;// Read the "gpl.txt" text file from its URL representationSystem.out.println("/***** File content (URL4) *****/n");while((inputLine = in.readLine()) != null) {System.out.println(inputLine);}} catch (IOException ioe) {ioe.printStackTrace(System.err);}} catch (MalformedURLException mue) {mue.printStackTrace(System.err);}}}Let’s explain the methods used in the above example.
URL(String spec)– Creates a URL object from the String representation. This constructor is equivalent to a call to the two-argument constructor with anull first argument.URL(URL context, String spec)– Creates a URL by parsing the givenspec within a specifiedcontext. The new URL is created from the givencontext URL and thespec argument as described inRFC2396 "Uniform Resource Identifiers" Generic Syntax.URL(String protocol, String host, String file)– Creates a URL from the specifiedprotocol name,host name, andfile name. The default port for the specified protocol is used.openStream()– Opens a connection to this URL and returns anInputStreamfor reading from that connection.(String protocol, String host, int port, String file)– Creates a URL object from the specifiedprotocol,host,port number, andfile.host can be expressed as a host name or a literal IP address. Specifying aport number of -1 indicates that the URL should use the default port for the protocol.
If we run the above code, we will get the following results:
URL1: http://www.gnu.orgURL2: http://www.gnu.org/licenses/gpl.txtURL3: http://www.gnu.org/licenses/gpl.txtURL4: http://www.gnu.org:80/licenses/gpl.txt/***** File content (URL4) *****/ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license forsoftware and other kinds of works. The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,the GNU General Public License is intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users. We, the Free Software Foundation, use theGNU General Public License for most of our software; it applies also toany other work released this way by its authors. You can apply it toyour programs, too.
2. Some more methods of the java.net.URL class
JavaNetURLMoreMethodsExample.java
package com.javacodegeeks.examples;import java.io.IOException;import java.net.URL;public class JavaNetURLMoreMethodsExample {public static void main(String[] args) {try {// Creates a URL object from the String representation.URL url = new URL("http://www.gnu.org/licenses/gpl.txt");// Gets the authority part of this URL.System.out.println("URL Authority: " + url.getAuthority());// Gets the default port number of the protocol associated with this URL.System.out.println("URL Default Port: " + url.getDefaultPort());// Gets the file name of this URL.System.out.println("URL File Name: " + url.getFile());// Gets the host name of this URL, if applicable.System.out.println("URL Host Name: " + url.getHost());// Gets the path part of this URL.System.out.println("URL Path: " + url.getPath());// Gets the protocol name of this URL.System.out.println("URL Protocal Name: " + url.getProtocol());} catch (IOException ioe) {ioe.printStackTrace(System.err);}}}Let’s explain the methods used in the above example.
getAuthority()– Gets the authority part of this URL.getDefaultPort()– Gets the default port number of the protocol associated with this URL. If the URL scheme or the URLStreamHandler for the URL do not define a default port number, then -1 is returned.getFile()– Gets the file name of this URL, or an empty string if one does not exist.getHost()– Gets the host name of this URL, if applicable. The format of the host conforms toRFC2732, i.e. for a literal IPv6 address, this method will return the IPv6 address enclosed in square brackets (‘[‘ and ‘]’).getPath()– Gets the path part of this URL, or an empty string if one does not exist.getProtocol()– Gets the protocol name of this URL.
If we run the above code, we will get the following results:
URL Authority: www.gnu.orgURL Default Port: 80URL File Name: /licenses/gpl.txtURL Host Name: www.gnu.orgURL Path: /licenses/gpl.txtURL Protocal Name: http
3. Download the source code
You can download the source code of this example from here:JavaNetURLClass.zip

Thank you!
We will contact you soon.



