- Java URL Class Example | Create, Read and Parse URL
- What is a URL ?
- What is URL class in Java?
- Constructor and Method of URL class
- How to Create URL in Java
- How to open and read from a URL in Java
- How to Read from URL and write to file in Java
- How to Parse URL
- Other interesting articles which you may like …
- Leave a Reply Cancel reply
- Lesson: Working with URLs
- What Is a URL?
- Creating a URL
- Parsing a URL
- Reading Directly from a URL
- Connecting to a URL
- Reading from and Writing to a URLConnection
Java URL Class Example | Create, Read and Parse URL
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
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
Other interesting articles which you may like …
- RSA Encryption and Decryption
- Java URL Encode and Decode Example
- Java Salted Password Hashing
- Google Tink Example – Google Cryptography
- AES 256 Encryption and Decryption
- AES 128 Encryption and Decryption
- Constructor in Java
- Private Constructors in Java
- Java Constructor Chaining with example
- Java – Constructor in an Interface?
- Constructor.newInstance() method
- Parameterized Constructor in Java
- Java 8 – Lambda Expressions
- Java 8 – ForEach Example
- Java 8 Default Methods in Interface
- Multiple Inheritance in Java 8 through Interface
- Java 9 – jdeprscan
- Private Methods in Interfaces Java 9
- Java Method Overloading Example
- Java Constructor Overloading Example
- Java this keyword | Core Java Tutorial
- Java super keyword
- Abstract Class in Java
- Interface in Java and Uses of Interface in Java
- What is Marker Interface
- Serialization and Deserialization in Java with Example
- Generate SerialVersionUID in Java
- Java Autoboxing and Unboxing Examples
- Use of Java Transient Keyword – Serailization Example
- Use of static Keyword in Java
- What is Method Overriding in Java
- Encapsulation in Java with Example
- Final Keyword in Java | Java Tutorial
- Java Static Import
- Java – How System.out.println() really work?
- Java Ternary operator
- Java newInstance() method
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Lesson: Working with URLs
URL is the acronym for Uniform Resource Locator. It is a reference (an address) to a resource on the Internet. You provide URLs to your favorite Web browser so that it can locate files on the Internet in the same way that you provide addresses on letters so that the post office can locate your correspondents.
Java programs that interact with the Internet also may use URLs to find the resources on the Internet they wish to access. Java programs can use a class called URL in the java.net package to represent a URL address.
The term URL can be ambiguous. It can refer to an Internet address or a URL object in a Java program. Where the meaning of URL needs to be specific, this text uses «URL address» to mean an Internet address and » URL object» to refer to an instance of the URL class in a program.
What Is a URL?
A URL takes the form of a string that describes how to find a resource on the Internet. URLs have two main components: the protocol needed to access the resource and the location of the resource.
Creating a URL
Within your Java programs, you can create a URL object that represents a URL address. The URL object always refers to an absolute URL but can be constructed from an absolute URL, a relative URL, or from URL components.
Parsing a URL
Gone are the days of parsing a URL to find out the host name, filename, and other information. With a valid URL object you can call any of its accessor methods to get all of that information from the URL without doing any string parsing!
Reading Directly from a URL
This section shows how your Java programs can read from a URL using the openStream() method.
Connecting to a URL
If you want to do more than just read from a URL, you can connect to it by calling openConnection() on the URL. The openConnection() method returns a URLConnection object that you can use for more general communications with the URL, such as reading from it, writing to it, or querying it for content and other information.
Reading from and Writing to a URLConnection
Some URLs, such as many that are connected to cgi-bin scripts, allow you to (or even require you to) write information to the URL. For example, a search script may require detailed query data to be written to the URL before the search can be performed. This section shows you how to write to a URL and how to get results back.