Java URL Class: Parse a URL with Examples

Java · Lesson 22 of 22

Java can read the parts of a web address (URL) with the URL class from the java.net package. A URL has a protocol, a host, a port, a file path and a reference.

MethodWhat it returns
getProtocol()The protocol, for example http
getHost()The host name of the server
getPort()The port number, or -1 if none is given
getFile()The file name and path
getRef()The part after the # sign

Example: parsing a URL

Parsing a URL...

Example : ParseURL

import java.net.*;
import java.io.*;
public class ParseURL
{
public static void main(String[] args)throws Exception
{
URL aURL=new URL("http://java.sun.com;80/docs/books/tutorial/intro.html#DOWNLOAD");
System.out.println("protocol="+aURL.getProtocol());
System.out.println("host="+aURL.getHost());
System.out.println("filename="+aURL.getFile());
System.out.println("port="+aURL.getPort());
System.out.println("ref="+aURL.getRef());
}
}
Unit-21 Networking (URL,SOCKETS (TCP/IP),DATAGRAMS) - II illustration
Output : ParseURL

Test what you learned

1 free Java test with instant scores.

Take a Java test

More Java lessons

Learn it in a course

WhatsApp us