URL
Parse URL example
In this example we shall show you how to parse a URL. Class URL represents a Uniform Resource Locator, a pointer to a “resource” on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine. To parse a URL one should perform the following steps:
- Create a URL object from the String representation.
- Use
getProtocol()
API method to get the protocol name of this URL, that is HTTP protocol. - Use
getHost()
API method to get the host name of this URL, if applicable. - Use
getPort()
API method to get the port number of this URL. - Use
getPath()
API method to get the path part of this URL,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.net.MalformedURLException; import java.net.URL; public class ParseURLExample { public static void main(String[] args) { // Create a URL try { URL url = new URL("http://www.javacodegeeks.com:80/"); String protocol = url.getProtocol(); String host = url.getHost(); int port = url.getPort(); String path = url.getPath(); System.out.println("URL created: " + url); System.out.println("protocol: " + protocol); System.out.println("host: " + host); System.out.println("port: " + port); System.out.println("path: " + path); } catch (MalformedURLException e) { System.out.println("Malformed URL: " + e.getMessage()); } } }
Output:
URL created: http://www.javacodegeeks.com:80/
protocol: http
host: www.javacodegeeks.com
port: 80
path: /
This was an example of how to parse a URL in Java.