URL
Parse URL example
In this example we shall show you how to parse aURL. 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 aURL 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 URLtry {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: httphost: www.javacodegeeks.comport: 80path: /
This was an example of how to parse a URL in Java.
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!
We will contact you soon.
Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor atJava Code Geeks.



