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.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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 { 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.