URL Class in Java

Anybody who uses the internet these days would have come across a URL. It is a unique string of text that is an identity for the resources available on the internet. To put it in simple words, a URL is an address for the resources that we can find on the internet. This article explains the URL class in Java. Let’s start!!

What is URL?

The term URL is an acronym for Uniform Resource Locator. It denotes a resource that is present on the World Wide Web. This resource might be an HTML page, file, or document that is present on the World Wide Web.

Segments of a URL:

Though a URL might consist of several components, it consists of three main parts.:

1. Protocol: In the above-given example, HTTP is the protocol. Some other examples of protocols are HTTPS, FTP, and File.

2. Server name or IP address: The server machine where the resources are present is denoted as the server’s name. Here, firstcode.com is the server name.

3. Filename: Here, the file name is “java-class-and-objects”.

4. Port number: Port number helps the URL connect with the web. In case of not explicitly mentioning the URL, the default port number is used.

Java URL Class

The Java URL is the gateway to access any resource that is present on the web. The object of the java.net.URL class denotes the URL and manages all the details available in the URL string. This class consists of various methods to create an object of the URL class.

S.No Constructor Description
1 URL(String address) throwsMalformedURLException It creates a URL object from the given input String
2 URL(String protocol, String host, String file) It creates a URL object from the input protocol, host and file name.
3 URL(String protocol, String host, int port, String file) It creates a URL object from the mentioned protocol, hostname, port number and, file name.
4 URL(URL context, String spec) It creates a URL object by passing the String specifications that are given.
5 URL(String protocol, String host, int port, String file, URLStreamHandler handler) It creates a URL object from the given protocol, hostname, port number, file, and, handler.
6 URL(URL context, Strong spec, URLStreamHandler handler) It makes a URL by parsing the spec with the input handler.

Methods of Java URL Class:

S.N Method Name Description
1 public String toString() It returns the given URL object in the string form.
2 public String getPath() It returns the path of the URL. It returns null if the URL is empty.
3 public String getQuery() It gives the query part of the URL. This part of the URL is present after the ‘?’ in it.
4 public String getAuthority() It returns the authority part of the URL. And it returns null if it is empty.
5 public String getHost() It gives the hostname related to the URL in IPv6 format
6 public String getFile() It returns the filename of the URL.
7 public int getPort() It returns the port number of the URL.
8 public int getDefaultPort()  It returns the default port number that the URL uses.
9 public String getRef() It returns the reference to the URL object. This reference is the part represented by ‘#’ in the URL.
10 public String getProtocol() It returns the protocol associated with the URL.
11 public String getAuthority() It returns the authority of the URL. It collects the hostname and the port.
12 public URL toURL() It returns a URL of the mentioned URL.
13 public URLConnection OpenConnection() It returns an instance of the URLConnection, connected with the particular URL.
14 public Object getContent() It returns the content of the URL, and it is returned as an Object.

Creating URL with Component Parts:

Let us now see how to create a URL using the SUL components like hostname, filename, and protocol.

Sample code to create a URL with the URL components:

import java.net.MalformedURLException;
import java.net.URL;
public class URLClassDemo
{
public static void main(String[ ] args) throws MalformedURLException
{
String protocol = "http";
String host = "firstcode.com";
String file = "/courses/java-url-class/";
URL url = new URL(protocol, host, file);   
System.out.println("The URL is: " +url.toString());
}
}

Output:

The URL is: http://firstcode.com/courses/java-url-class

Sample program to implement the URL Class of Java:

import java.net.MalformedURLException;
import java.net.URL;
public class URLClassDemo
{
public static void main(String[] args) throws MalformedURLException
{
URL url1 = new URL("https://firstcode.com/courses/java-encapsulation/");
System.out.println("url1 is: " +url1.toString());
System.out.println("\nVarious components of the url1");
System.out.println("Protocol: " + url1.getProtocol());
System.out.println("Hostname: " + url1.getHost());
System.out.println("Port: " + url1.getPort());
System.out.println("Default port: " + url1.getDefaultPort());
System.out.println("Query: " + url1.getQuery());
System.out.println("Path: " + url1.getPath());
System.out.println("File: " + url1.getFile());
System.out.println("Reference: " + url1.getRef());
System.out.println("Authority: " + url1.getAuthority());
}

Output:

url1 is: https://firstcode.com/courses/java-encapsulation/Various components of the url1
Protocol: https
Hostname: firstcode.com
Port: -1
Default port: 443
Query: null
Path: /courses/java-encapsulation/
File: /courses/java-encapsulation/
Reference: null
Authority: firstcode.com

URL Connection class in Java:

The URLConnection class in Java is important to represent a connection or communication between an application and the URL. it helps the programmers to read and write data to the given resource of the URL.

The java.net.URLConnection is an abstract class that has its subclasses representing the different types of URL connections.

For example:

  • The openConnection() method returns the object of the HttpURLConnection class. This takes place when we connect to a URL using the HTTP protocol.
  • The openConnection() method returns the object of a JarURLConnection class. this happens if we connect a JAR file to a URL.

Java OpenConnection() method:

We can attain the object of the URLConnection class with the openConnection() method of the URL class.

Syntax:

public URLConnection openConnection() throws IOException{}

Methods of URL Connection Class in Java:

Sl.N. Method  Description
1 Object getContent() It returns the contents of the URL connection.
2 String getContentEncoding() It returns the value of the content-encoding header field in the form of a String.
3 int getContentLength() This method provides the value of the content-length header field in the String form.
4 String getContentType() It returns the value of the content-type header field.
5 int getLastModified() It gives the value of the last-modified header field.
6 long getExpiration() It returns the value of the expired header field.
7 long getIfModifiedSince() It returns the value of the object’s ifModifiedSince field.
9 public void setDoInput(boolean input) The value true is passed as a parameter to this method to specify that it will be used for connection input. 
10 public void setDoOutput(boolean output) We pass the parameter true to this method to specify that we will use the connection output.
11 public InputStream getInputStream() throws IOException It returns the input stream of the URL connection for reading from the resource.
12 public OutputStream getOutputStream() throws IOException It returns the output stream of the URL connection for writing to the resource.
13 public URL getURL() Returns the URL of the connected URLConnection object.

Example of the URLConnection class:

As we just saw the various methods that are present in the URLConnectionDemo class, let us see an example program to implement it.

Sample program to implement URLConnection class:

import java.net.*;
import java.io.*;
public class URLConnectionDemo
{
public static void main(String[] args) throws MalformedURLException
{
try{
URL url = new URL("https://www.firstcode.com");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = null;
if(urlConnection instanceof HttpURLConnection)
{
connection = (HttpURLConnection) urlConnection; 
}
else
{
System.out.println("Please enter a HTTP URL: ");
return;
}
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String urlString = " ";
String current;
while((current = in.readLine()) != null)
{
urlString += current;
}
System.out.println(urlString);
} catch (IOException e)
{
e.printStackTrace();
}
}
}

Output:

…..a complete HTML content of the home page of firstcode.com…..

Illustration methods of Java URL class:

import java.net.*;
public class FirstCode
{
public static void main(String[] args)throws Exception{
String url="https://first-code/blogs/java-tutorial/";
URL testurl= new URL(url);
System.out.println("The String representation of the URL -> "+testurl.toString());
System.out.println("The Authority of the URL -> "+testurl.getAuthority());
System.out.println("The Path of the URL -> "+testurl.getPath());
System.out.println("The Query of the URL -> "+testurl.getQuery());
System.out.println("The Host of the URL -> "+testurl.getHost());
System.out.println("The File of the URL -> "+testurl.getFile());
System.out.println("The Port of the URL -> "+testurl.getPort());
System.out.println("The Default port of the URL -> "+testurl.getDefaultPort());
System.out.println("The Protocol of the URL -> "+testurl.getProtocol());
System.out.println("As no certain values can be parsed, the results are null or -1 in various cases, but there are no particular values.");
 
}
}

Output:

The string representation of the URL -> https://first-code/blogs/java-tutorial/
The Authority of the URL -> first-code.training
The Path of the URL -> /blogs/java-tutorial/
The Query of the URL -> null
The host of the URL -> first-code.training
The file of the URL -> /blogs/java-tutorial/
The port of the URL -> -1
The default port of the URL -> 443
The protocol of the URL -> https

As no certain values can be parsed, the results are null or -1 in various cases, but there are no particular values.

Sample program to implement url class in Java:

import java.net.MalformedURLException;
import java.net.URL;
public class FirstCode
{
public static void main(String[] args)throws MalformedURLException
{
URL url1 = new URL("https://www.google.co.in/?gfe_rd=cr&ei=ptYq" + "WK26I4fT8gfth6CACg#q=first+code+java+tutorials");
 
// creates a URL with a protocol,hostname,and path
URL url2 = new URL("http", "www.firstcode.com", "/jvm-works-jvm-architecture/");
 
URL url3 = new URL("https://www.google.co.in/search?"+ "q=gnu&rlz=1C1CHZL_enIN71" + "4IN715&oq=gnu&aqs=chrome..69i57j6" +"9i60l5.653j0j7&sourceid=chrome&ie=UTF" + "-8#q=first+code+java+tutorials");
 
// print the string representation of the URL.
System.out.println(url1.toString());
System.out.println(url2.toString());
System.out.println();
System.out.println("Different components of the URL3-");
 
// retrieve the protocol for the URL
System.out.println("Protocol:- " + url3.getProtocol());
 
// retrieve the hostname of the url
System.out.println("Hostname:- " + url3.getHost());
 
// retrieve the default port
System.out.println("Default port:- " +url3.getDefaultPort());
 
// retrieve the query part of URL
System.out.println("Query:- " + url3.getQuery());
 
// retrieve the path of URL
System.out.println("Path:- " + url3.getPath());
 
// retrieve the file name
System.out.println("File:- " + url3.getFile());
 
// retrieve the reference
System.out.println("Reference:- " + url3.getRef());
}
}

Output:

https://www.google.co.in/?gfe_rd=cr&ei=ptYqWK26I4fT8gfth6CACg#q= first+code+java+tutorials
https://www.first+code+java+tutorials/jvm-works-jvm-architecture/
Different components of the URL3-
Protocol -> https
Hostname -> www.google.co.in
Default port -> 443
Query -> q=gnu&rlz=1C1CHZL_enIN1416LK15&oq=gnu&aws=chrome..69i57j&sourceid=chrome&ie=UTF-8
Path -> /search
File -> /search?q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&as=chrome..69i57898015.6523joj7&sourceid-chrome&ie=UTF-8
References –> q=first+code+blogs+tutorial

Conclusion

The URL class is inevitable in the internet era. In this tutorial, we learned about the Java URL, its constructors, and methods. Now, you can easily establish the URL connection class to connect with an application.

Leave a Reply

Your email address will not be published. Required fields are marked *