Friday 9 October 2015

Java: URL: Represents a Uniform Resource Locator

URL class represents a Uniform Resource Locator in World Wide Web (WWW).

In general URL is broken down into number of parts like protocol, host, port, file to access.

For example,

In the above URL,
http : is access mechanism (protocol)
en.wikipedia.org : It is the host name
80 : is the port number
wiki/Uniform_resource_locator : Relative path to reach specific resource.

Note:
Port number is optional, If the port is not specified, the default port for the protocol is used.

One more thing to note is, URL class don’t encode the spaces between URL, it is your responsibility to encode URL properly. URLEncoder class is used to achieve this.

For example, following two URLs are not equal.
http://foo.com/hello world/

URL class provides following constructors, to create an instance of URL class.

URL(String spec)
URL(String protocol, String host, int port, String file)
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
URL(String protocol, String host, String file)
URL(URL context, String spec)
URL(URL context, String spec, URLStreamHandler handler)


import java.net.MalformedURLException;
import java.net.URL;

public class Main {
  public static void main(String args[]) throws MalformedURLException {

    String location = "https://self-learning-java-tutorial.blogspot.com/2014/02/creating-object.html";
    URL url = new URL(location);

    System.out.println("Protocol used: " + url.getProtocol());
    System.out.println("Host name : " + url.getHost());
    System.out.println("File: " + url.getFile());
    System.out.println("Default Port: " + url.getDefaultPort());

  }
}


Output
Protocol used: http
Host name : self-learning-java-tutorial.blogspot.com
File: /2014/02/creating-object.html
Default Port: 80




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment