URL

java.net.URL Example

Photo of Armando FloresArmando FloresJune 11th, 2014Last Updated: June 12th, 2014
0 1,001 4 minutes read

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.

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

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Armando FloresArmando FloresJune 11th, 2014Last Updated: June 12th, 2014
0 1,001 4 minutes read
Photo of Armando Flores

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.

Related Articles

Bipartite Graph

Convert between URL and URI

November 11th, 2012
Bipartite Graph

Parse URL example

November 11th, 2012
Bipartite Graph

Read text from URL

November 11th, 2012
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.