- Creating a URL
- Creating a URL Relative to Another
- Other URL Constructors
- URL addresses with Special characters
- MalformedURLException
- How to build url in java?
- Method 1: Using the URL Constructor
- Method 2: Using the URI class
- Method 3: Using the URLEncoder class
- Method 4: Using the UriBuilder class (Java 11+)
Creating a URL
The easiest way to create a URL object is from a String that represents the human-readable form of the URL address. This is typically the form that another person will use for a URL. In your Java program, you can use a String containing this text to create a URL object:
URL myURL = new URL("http://example.com/");
The URL object created above represents an absolute URL. An absolute URL contains all of the information necessary to reach the resource in question. You can also create URL objects from a relative URL address.
Creating a URL Relative to Another
A relative URL contains only enough information to reach the resource relative to (or in the context of) another URL.
Relative URL specifications are often used within HTML files. For example, suppose you write an HTML file called JoesHomePage.html . Within this page, are links to other pages, PicturesOfMe.html and MyKids.html , that are on the same machine and in the same directory as JoesHomePage.html . The links to PicturesOfMe.html and MyKids.html from JoesHomePage.html could be specified just as file names, like this:
These URL addresses are relative URLs. That is, the URLs are specified relative to the file in which they are contained — JoesHomePage.html .
In your Java programs, you can create a URL object from a relative URL specification. For example, suppose you know two URLs at the site example.com :
http://example.com/pages/page1.html http://example.com/pages/page2.html
You can create URL objects for these pages relative to their common base URL: http://example.com/pages/ like this:
URL myURL = new URL("http://example.com/pages/"); URL page1URL = new URL(myURL, "page1.html"); URL page2URL = new URL(myURL, "page2.html");
This code snippet uses the URL constructor that lets you create a URL object from another URL object (the base) and a relative URL specification. The general form of this constructor is:
URL(URL baseURL, String relativeURL)
The first argument is a URL object that specifies the base of the new URL . The second argument is a String that specifies the rest of the resource name relative to the base. If baseURL is null, then this constructor treats relativeURL like an absolute URL specification. Conversely, if relativeURL is an absolute URL specification, then the constructor ignores baseURL .
This constructor is also useful for creating URL objects for named anchors (also called references) within a file. For example, suppose the page1.html file has a named anchor called BOTTOM at the bottom of the file. You can use the relative URL constructor to create a URL object for it like this:
URL page1BottomURL = new URL(page1URL,"#BOTTOM");
Other URL Constructors
The URL class provides two additional constructors for creating a URL object. These constructors are useful when you are working with URLs, such as HTTP URLs, that have host name, filename, port number, and reference components in the resource name portion of the URL. These two constructors are useful when you do not have a String containing the complete URL specification, but you do know various components of the URL.
For example, suppose you design a network browsing panel similar to a file browsing panel that allows users to choose the protocol, host name, port number, and filename. You can construct a URL from the panel’s components. The first constructor creates a URL object from a protocol, host name, and filename. The following code snippet creates a URL to the page1.html file at the example.com site:
new URL("http", "example.com", "/pages/page1.html");
new URL("http://example.com/pages/page1.html");
The first argument is the protocol, the second is the host name, and the last is the pathname of the file. Note that the filename contains a forward slash at the beginning. This indicates that the filename is specified from the root of the host.
The final URL constructor adds the port number to the list of arguments used in the previous constructor:
URL gamelan = new URL("http", "example.com", 80, "pages/page1.html");
This creates a URL object for the following URL:
http://example.com:80/pages/page1.html
If you construct a URL object using one of these constructors, you can get a String containing the complete URL address by using the URL object’s toString method or the equivalent toExternalForm method.
URL addresses with Special characters
Some URL addresses contain special characters, for example the space character. Like this:
http://example.com/hello world/
To make these characters legal they need to be encoded before passing them to the URL constructor.
URL url = new URL("http://example.com/hello%20world");
Encoding the special character(s) in this example is easy as there is only one character that needs encoding, but for URL addresses that have several of these characters or if you are unsure when writing your code what URL addresses you will need to access, you can use the multi-argument constructors of the java.net.URI class to automatically take care of the encoding for you.
URI uri = new URI("http", "example.com", "/hello world/", "");
And then convert the URI to a URL.
MalformedURLException
Each of the four URL constructors throws a MalformedURLException if the arguments to the constructor refer to a null or unknown protocol. Typically, you want to catch and handle this exception by embedding your URL constructor statements in a try / catch pair, like this:
try < URL myURL = new URL(. ); >catch (MalformedURLException e) < // exception handler code here // . >
See Exceptions for information about handling exceptions.
URL s are «write-once» objects. Once you’ve created a URL object, you cannot change any of its attributes (protocol, host name, filename, or port number).
How to build url in java?
Building a URL in Java involves creating an instance of the URL class and passing in the desired URL string as the parameter. However, there are a few things to keep in mind when constructing a URL in Java, such as properly encoding any special characters and handling exceptions that may be thrown. In this guide, we will discuss several different ways to build a URL in Java and address some common pitfalls to watch out for.
Method 1: Using the URL Constructor
Building a URL in Java can be done in various ways, but one of the simplest methods is by using the URL constructor. This constructor takes a string representation of the URL as its argument and creates a URL object that can be used to perform various operations on the URL.
Here is an example code snippet that demonstrates how to use the URL constructor to build a URL:
import java.net.*; public class URLBuilder public static void main(String[] args) throws MalformedURLException // Step 1: Create an instance of the URL class URL url = new URL("https://www.example.com/path/to/resource?param1=value1¶m2=value2"); // Step 2: Retrieve various components of the URL String protocol = url.getProtocol(); // "https" String host = url.getHost(); // "www.example.com" int port = url.getPort(); // -1 (default port for "https" is 443) String path = url.getPath(); // "/path/to/resource" String query = url.getQuery(); // "param1=value1¶m2=value2" // Step 3: Print the components of the URL System.out.println("Protocol: " + protocol); System.out.println("Host: " + host); System.out.println("Port: " + port); System.out.println("Path: " + path); System.out.println("Query: " + query); > >
In this example, we create a URL object by passing a string representation of the URL to the URL constructor. We then retrieve various components of the URL using the getter methods provided by the URL class. Finally, we print the components of the URL to the console.
Note that the URL constructor can throw a MalformedURLException if the string representation of the URL is invalid. Therefore, it is important to handle this exception appropriately.
That’s it! By following these simple steps, you can easily build a URL in Java using the URL constructor.
Method 2: Using the URI class
To build a URL in Java using the URI class, follow these steps:
import java.net.URI; import java.net.URISyntaxException;
URI uri; try uri = new URI("https://www.example.com/path/to/resource?key1=value1&key2=value2#fragment"); > catch (URISyntaxException e) // handle exception >
String scheme = uri.getScheme(); // "https" String authority = uri.getAuthority(); // "www.example.com" String host = uri.getHost(); // "www.example.com" int port = uri.getPort(); // -1 (default port for https) String path = uri.getPath(); // "/path/to/resource" String query = uri.getQuery(); // "key1=value1&key2=value2" String fragment = uri.getFragment(); // "fragment"
uri = uri.resolve("/new/path"); // changes path to "/new/path"
String url = uri.toString(); // "https://www.example.com/new/path?key1=value1&key2=value2#fragment"
Here is the complete code with all the examples:
import java.net.URI; import java.net.URISyntaxException; public class UrlBuilder public static void main(String[] args) URI uri; try uri = new URI("https://www.example.com/path/to/resource?key1=value1&key2=value2#fragment"); > catch (URISyntaxException e) // handle exception return; > String scheme = uri.getScheme(); // "https" String authority = uri.getAuthority(); // "www.example.com" String host = uri.getHost(); // "www.example.com" int port = uri.getPort(); // -1 (default port for https) String path = uri.getPath(); // "/path/to/resource" String query = uri.getQuery(); // "key1=value1&key2=value2" String fragment = uri.getFragment(); // "fragment" System.out.println("Scheme: " + scheme); System.out.println("Authority: " + authority); System.out.println("Host: " + host); System.out.println("Port: " + port); System.out.println("Path: " + path); System.out.println("Query: " + query); System.out.println("Fragment: " + fragment); uri = uri.resolve("/new/path"); System.out.println("Modified Path: " + uri.getPath()); String url = uri.toString(); System.out.println("URL: " + url); > >
This code will output the following:
Scheme: https Authority: www.example.com Host: www.example.com Port: -1 Path: /path/to/resource Query: key1=value1&key2=value2 Fragment: fragment Modified Path: /new/path URL: https://www.example.com/new/path?key1=value1&key2=value2#fragment
That’s it! You have successfully built a URL in Java using the URI class.
Method 3: Using the URLEncoder class
To build a URL in Java using the URLEncoder class, follow these steps:
import java.net.URLEncoder; import java.io.UnsupportedEncodingException;
String baseURL = "http://example.com/search?"; String query = "java programming"; String charset = "UTF-8";
String encodedQuery = URLEncoder.encode(query, charset);
String finalURL = baseURL + "q token operator">+ encodedQuery;
Here is the complete code:
import java.net.URLEncoder; import java.io.UnsupportedEncodingException; public class URLBuilder public static void main(String[] args) throws UnsupportedEncodingException String baseURL = "http://example.com/search?"; String query = "java programming"; String charset = "UTF-8"; String encodedQuery = URLEncoder.encode(query, charset); String finalURL = baseURL + "q token operator">+ encodedQuery; System.out.println(finalURL); > >
http://example.com/search?q=java+programming
Note that the URLEncoder class throws an UnsupportedEncodingException, which must be caught or thrown by the calling method.
Method 4: Using the UriBuilder class (Java 11+)
To build a URL in Java using the UriBuilder class in Java 11+, you can follow these steps:
import java.net.URI; import java.net.URISyntaxException; import javax.ws.rs.core.UriBuilder;
UriBuilder builder = UriBuilder.fromPath("https://www.example.com");
builder.path("api").path("v1").path("users");
builder.queryParam("name", "John").queryParam("age", 30);
Here is the complete example code:
import java.net.URI; import java.net.URISyntaxException; import javax.ws.rs.core.UriBuilder; public class UrlBuilderExample public static void main(String[] args) throws URISyntaxException UriBuilder builder = UriBuilder.fromPath("https://www.example.com"); builder.path("api").path("v1").path("users"); builder.queryParam("name", "John").queryParam("age", 30); URI uri = builder.build(); System.out.println(uri.toString()); > >
https://www.example.com/api/v1/users?name=John&age=30
In this example, we first imported the necessary classes. Then, we created a UriBuilder instance with the base URL. We added path segments to the URL using the path() method and query parameters using the queryParam() method. Finally, we built the URI using the build() method and printed it to the console.
Note that the UriBuilder class provides many other methods for building URLs, such as scheme() , host() , port() , fragment() , etc. You can refer to the Java documentation for more information.