URL

java.net.URL Example

In this example, we will show the range of functionality provided by the java.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 network host or server, the name of the resource, its location on that host, and a protocol by which the host should communicate: protocol://hostname/path/resource-name.

protocol is an identifier such as http or ftp; hostname is usually an Internet host and domain name; and the path and resource-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 the http 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.org
			URL url1 = new URL("http://www.gnu.org");
			System.out.println("URL1: " + url1.toString());

			// Generate URL for pages with a common base
			URL url2 = new URL(url1, "licenses/gpl.txt");
			System.out.println("URL2: " + url2.toString());

			// Generate URLs from different pieces of data
			URL 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 line
			try (BufferedReader in = new BufferedReader(new InputStreamReader(url4.openStream()))) {
				String inputLine;

				// Read the "gpl.txt" text file from its URL representation
				System.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.

If we run the above code, we will get the following results:

URL1: http://www.gnu.org
URL2: http://www.gnu.org/licenses/gpl.txt
URL3: http://www.gnu.org/licenses/gpl.txt
URL4: 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 for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your 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 to RFC2732, 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.org
URL Default Port: 80
URL File Name: /licenses/gpl.txt
URL Host Name: www.gnu.org
URL Path: /licenses/gpl.txt
URL Protocal Name: http

 

3. Download the source code

You can download the source code of this example from here: JavaNetURLClass.zip

Armando Flores

Armando graduated from from Electronics Engineer in the The Public University Of Puebla (BUAP). He also has a Masters degree in Computer Sciences from CINVESTAV. He has been using the Java language for Web Development for over a decade. He has been involved in a large number of projects focused on "ad-hoc" Web Application based on Java EE and Spring Framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button