Java URL class

Introduction

Java's URL class has several constructors and each can throw a MalformedURLException.

URL(String urlSpecifier) throws MalformedURLException 
URL(String protocolName, String hostName, int port, String path)throws MalformedURLException 
URL(String protocolName, String hostName, String path )throws MalformedURLException 
URL(URL urlObj, String  urlSpecifier) throws MalformedURLException 
// Demonstrate URL. 
import java.net.MalformedURLException;
import java.net.URL;

public class Main {
   public static void main(String args[]) throws MalformedURLException {
      URL hp = new URL("http://www.google.com");

      System.out.println("Protocol: " + hp.getProtocol());
      System.out.println("Port: " + hp.getPort());
      System.out.println("Host: " + hp.getHost());
      System.out.println("File: " + hp.getFile());
      System.out.println("Ext:" + hp.toExternalForm());
   }/* www .j  av  a 2  s. c  om*/
}
import java.net.URL; 

public class Main { 
    public static void main(String[] args) { 
        String baseURLStr = "http://www.ietf.org/rfc/rfc3986.txt"; 
        String relativeURLStr = "rfc2732.txt"; 
        try { /*from   w  w w  .  j a v a2s . c  o m*/
            URL baseURL = new URL(baseURLStr); 
            URL resolvedRelativeURL = new URL(baseURL, relativeURLStr); 
            System.out.println("Base URL:" + baseURL); 
            System.out.println("Relative URL String:" + relativeURLStr); 
            System.out.println("Resolved Relative URL:" + resolvedRelativeURL); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
} 



PreviousNext

Related