Java URL Class represents the URL [Uniform Resource Locator], through which you can locate and retrieve data from the network. The URL Class in Java enables us to get the data without the need to worry about the way to communicate with the server, or the protocol which needs to be used during the communication or the format of the message which will be returned.
What is a URL ?
URL stands for Uniform Resource Locator. A URL is nothing more than the address of a given unique resource on the Web, in simple word each valid URL will be pointing a unique resource such a file, HTML page, document etc.
URL has two main components – Protocol and Resource name
Let’s look into the below url
https://www.javainterviewpoint.com/
Protocol : For the above URL the protocol is “https”
Resource name: javainterviewpoint.com will be the Resource Name
Further more the Resource can be split into
Host name : This is the name of the machine where the particular resource exists
Filename: Path of the file where the file in the machine
Port Number: The port to which we need to connect to the server, this mostly optional if the web server uses the standard ports of the HTTP protocol [80 for HTTP and 443 for HTTPS]
What is URL class in Java?
The java.net.URL class is a Final Class [Cannot be sub classed] extends java.lang.Object, The URL Class in Java supports many protocols such as “http”, “ftp”, “file”, “mailto”, “gopher” etc…
The URL Class uses a protocol handler to establish a connection with a server and use the protocol which is necessary to retrieve data. For example, an HTTP protocol handler knows how to talk to an HTTP server and retrieve a document, likewise an FTP protocol handler knows how to talk to an FTP server and retrieve a file.
Constructor and Method of URL class
The Java URL Class provides several constructors for creating the URLs.
Constructor | Description |
---|---|
URL(String url) throws MalformedURLException | This constructor creates the URL object from the specified String |
URL(String protocol, String host, int port, String file) throws MalformedURLException | This constructor creates the URL object using the specified protocol, host, port number, and file |
URL(String protocol, String host, int port, String file, URLStreamHandler handler) | This constructor creates the URL object using the specified protocol, host, port number, file, and handler |
URL(String protocol, String host, String file) | This Constructor creates the URL from the specified protocol, host, and file |
URL(URL context, String spec) | This Constructors creates the URL by parsing the given spec within the context |
URL(URL context, String spec, URLStreamHandler handler) | This Constructors creates a URL by parsing the given spec with the specified handler within the context |
Some of the important Methods of the URL Class
Methods | Description |
---|---|
public String getQuery() | This Method gets the query part of the URL |
public String getPath() | This Method gets the path part of the URL |
public String getUserInfo() | This Method gets the user information of the URL |
public String getAuthority() | This Method gets the authority information of the URL |
public int getPort() | This Method gets the port number of the URL |
public int getDefaultPort() | This Method gets the default port number of the protocol which is associated with the URL |
public String getProtocol() | This Method gets the protocol name of the URL |
public String getHost() | This Method gets host name of the URL, format conforms to RFC 2732 |
public String getFile() | This Method gets the file name of the URL, it will be same as getPath() when there is no query parameter |
public String getRef() | This Method gets the anchor / reference of the URL |
How to Create URL in Java
Creating URL using URL Class is pretty simple, We can simply make use of the URL Class constructors to create a URL. Let’s understand few different ways to create URL objects.
package com.javainterviewpoint; import java.net.MalformedURLException; import java.net.URL; public class CreateURL { public static void main(String[] args) { try { // Create a new absolute URL URL url1 = new URL ("https://www.javainterviewpoint.com/"); System.out.println(url1.toString()); // Create a relative URL URL url2 = new URL (url1,"/star-pattern-programs-in-java/"); System.out.println(url2.toString()); // Create URL passing the Protocol, Hostname, Path URL url3 = new URL ("https", "www.javainterviewpoint.com", "/star-pattern-programs-in-java/"); System.out.println(url3.toString()); // Create URL passing the Protocol, Hostname, port number, Path URL url4 = new URL ("https", "www.javainterviewpoint.com", 443, "/star-pattern-programs-in-java/"); System.out.println(url4.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } } }
This is the easiest way to create a URL, all you need to do is that pass the URL string [absolute URL] of the resource to constructor of the URL class.
URL url1 = new URL (“https://www.javainterviewpoint.com/”);
In the second approach of creating URL, we will be creating a relative URL by passing the path relative to the base URL. The first argument is a URL object that specifies the base URL and the second argument is a String that specifies the resource name relative to the base URL. This approach comes handy when your site has a lot different pages, you can create the URL of the pages relative to the URL of the main site [Base URL].
URL url2 = new URL (url1,”/star-pattern-programs-in-java/”);
If baseURL is null, then the constructor treats relativeURL as an absolute URL and if relative URL is treated as an absolute URL, then the constructor ignores baseURL.
The Third and fourth approach will be useful when you have the entites of the URL such as protocol, host name, filename, port number, and reference components separately. Say for example, if you have a screen which has the options for the users to select the Protocol, port, host etc.. Then we can use the below constructors to build the URL objects.
URL url3 = new URL (“https”, “www.javainterviewpoint.com”, “/star-pattern-programs-in-java/”);
URL url4 = new URL (“https”, “www.javainterviewpoint.com”, 443, “/star-pattern-programs-in-java/”);
How to open and read from a URL in Java
Since we have created the URL using the above approaches, let’s see how to open and read from a URL in Java.
package com.javainterviewpoint; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; public class ReadURL { public static void main(String[] args) { try { URL url = new URL ("https://www.google.com"); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( url.openStream())); String input; while ((input = bufferedReader.readLine()) != null) { System.out.println(input); } bufferedReader.close(); } catch (MalformedURLException me) { me.printStackTrace(); } catch (IOException ie) { ie.printStackTrace(); } } }
- Create a new URL object, passing in the URL string which we need to access to the URL class constructor
- The openStream() method returns InputStream which can be passed to the bufferedReader.
- Using the BufferedReader’s readLine() method which returns the content of the URL.
How to Read from URL and write to file in Java
let’s see how to read from URL and write to file in Java
package com.javainterviewpoint; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; public class WriteURL { public static void main(String[] args) { FileOutputStream fileOutputStream = null; BufferedReader bufferedReader = null; try { URL url = new URL ("https://www.google.com"); bufferedReader = new BufferedReader( new InputStreamReader( url.openStream())); fileOutputStream = new FileOutputStream("D:\\JIP\\test.txt"); String input; while ((input = bufferedReader.readLine()) != null) { System.out.println(input); fileOutputStream.write(input.getBytes()); } bufferedReader.close(); fileOutputStream.close(); } catch (MalformedURLException me) { me.printStackTrace(); } catch (IOException ie) { ie.printStackTrace(); } } }
- Create a new URL object and pass the URL of the resource to the constructor.
- Read the content of the URL using the bufferedReader.
- The readLine() method of the BufferedReader which reads the content of the URL
- Write the content to a file using the write() method of the FileOutputStream.
How to Parse URL
Let’s parse URL and get the different components which makes up the URL
package com.javainterviewpoint; import java.net.MalformedURLException; import java.net.URL; public class ParseURL { public static void main(String[] args) { try { URL url = new URL ("https://www.google.com/search?q=url+class+in+java#java"); System.out.println("Protocol : " + url.getProtocol()); System.out.println("File : " + url.getFile()); System.out.println("Host : " + url.getHost()); System.out.println("Port : " + url.getPort()); System.out.println("Path : " + url.getPath()); System.out.println("Query : " + url.getQuery()); System.out.println("UserInfo : " + url.getUserInfo()); System.out.println("Authority : " + url.getAuthority()); System.out.println("DefaultPort : " + url.getDefaultPort()); System.out.println("Reference : " + url.getRef()); } catch (MalformedURLException me) { me.printStackTrace(); } } }
- getProtocol() – Returns the name of the protocol used in the URL
- getFile() – Returns the complete path, including the query string
- getHost() – Returns the name of the Host
- getPort() – Returns the port using in the URL, returns -1 when the port number is not explicitly specified
- getPath() – Return the path of the URL, excluding the query string
- getQuery() – Returns the query string of the URL
- getUserInfo() – Returns the user information
- getAuthority() – Returns the authority information of the URL
- getDefaultPort() – Returns the default port of the URL, example 443 for HTTPS and 80 for HTTP
- getRef() – Returns the anchor element present in the URL
Output:
Protocol : https File : /search?q=url+class+in+java Host : www.google.com Port : -1 Path : /search Query : q=url+class+in+java UserInfo : null Authority : www.google.com DefaultPort : 443
Leave a Reply