Java URL

Posted By on April 29, 2016


Download PDF
TCP/IP client sockets
InetAddress Class

URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a Web page or FTP directory.

This section shows you how to write Java programs that communicate with a URL. A URL can be broken down into parts, as follows:

protocol://host:port/path?query#ref

Examples of protocols include HTTP, HTTPS, FTP, and File. The path is also referred to as the filename, and the host is also called the authority.

The following is a URL to a Web page whose protocol is HTTP:

http://www.amrood.com/index.htm?language=en#j2se

Notice that this URL does not specify a port, in which case the default port for the protocol is used. With HTTP, the default port is 80.

URL Class Methods:
The java.net.URL class represents a URL and has complete set of methods to manipulate URL in Java.

 

SN Methods with Description
1 public URL(String protocol, String host, int port, String file) throws MalformedURLException.
Creates a URL by putting together the given parts.
2 public URL(String protocol, String host, String file) throws MalformedURLException
Identical to the previous constructor, except that the default port for the given protocol is used.
3 public URL(String url) throws MalformedURLException
Creates a URL from the given String
4 public URL(URL context, String url) throws MalformedURLException
Creates a URL by parsing the together the URL and String arguments

Example of Java URL class

import java.io.*;
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL(“http://www.world4engineer.com/java-urlclass”);

System.out.println(“Protocol: “+url.getProtocol());
System.out.println(“Host Name: “+url.getHost());
System.out.println(“Port Number: “+url.getPort());
System.out.println(“File Name: “+url.getFile());

}
catch(Exception e){System.out.println(e);}
}
}

 

Output:

Protocol: http
Host Name: www.world4engineers.com
Port Number: -1
File Name: /java-urlclass
TCP/IP client sockets
InetAddress Class

Download PDF