Open In App

Java.net.URI class in Java

Last Updated : 12 Jun, 2017
Improve
Improve
Like Article
Like
Save
Share
Report

This class provides methods for creating URI instances from its components or by parsing the string form of those components, for accessing and retrieving different components of a URI instance.
What is URI?
URI stands for Uniform Resource Identifier. A Uniform Resource Identifier is a sequence of characters used for identification of a particular resource. It enables for the interaction of the representation of the resource over the network using specific protocols.

URI, URL and URN: What is The Difference?

The question that must be coming to your minds must be that if URI identifies a resource, what does URL do? People often use the terms interchangeably but it is not correct. According to Tim Berners Lee

“A Uniform Resource Identifier (URI) is a compact sequence of characters that identifies an abstract or physical resource.”
“A URI can be further classified as a locator, a name, or both. The term “Uniform Resource Locator” (URL) refers to the subset of URI that identify resources via a representation of their primary access mechanism (e.g., their network “location”), rather than identifying the resource by name or by some other attribute(s) of that resource. The term “Uniform Resource Name” (URN) refers to the subset of URI that are required to remain globally unique and persistent even when the resource ceases to exist or becomes unavailable.”

For example,

https://www.geeksforgeeks.org/url-class-java-examples/

Represents a URL as it tells the exact location where url class article can be found over the network.

url-class-java-examples

Represents a URN as it does not tell anything about the location but only gives a unique name to the resource.

The difference between an object of URI class and an URL class lies in the fact that a URI string is parsed only with consideration of syntax and no lookups of host is performed on creation. Comparison of two URI objects is done solely on the characters contained in the string. But on the other hand, a URL string is parsed with a certain scheme and comparisons of two URL objects is performed by looking of actual resource on the net.

URI Syntax :

scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
  1. scheme : The scheme component lays out the protocols to be associated with the URI. In some schemes the “//” are required while others dont need them.
    abc://admin:admin@geeksforgeeks.org:1234/path/data
                 ?key=value&key2=value2#fragid1
  2. authority : Authority component is made of several components- authentication section, a host and optional port number preceded by a ‘:’. Authentication section includes username and password. Host can be any ip-address.
    abc://admin:admin@geeksforgeeks.org:1234/path/data
                 ?key=value&key2=value2#fragid1
  3. path : The path represents a string containing the address within the server to the resource.
    abc://admin:admin@geeksforgeeks.org:1234/path/data
                 ?key=value&key2=value2#fragid1
  4. query : Query represent a nonhierarchical data usually the query used for searching of a particular resource. They are separated by a ‘?’ from the preceding part.
    abc://admin:admin@geeksforgeeks.org:1234/path/data
                 ?key=value&key2=value2#fragid1
  5. fragment : Fragments are used to identify secondary resources as headings or subheadings within a page etc.
    abc://admin:admin@geeksforgeeks.org:1234/path/data
                 ?key=value&key2=value2#fragid1

Constructors :

  1. URI(String str) : Constructs a URI object by parsing the specified string. The grammar used while parsing is the one specified in RFC 2396, Appendix A.
    Syntax :public URI(String str)
        throws URISyntaxException
    Parameters : 
    str : String to be parsed into URI
    Throws : 
    URISyntaxException : If the string violates RFC 2396
  2. URI(String scheme, String ssp, String fragment) : Constructs a URI from the given components. A component may be left undefined by passing null. Initially the result string is empty. If scheme is not null it is appended. Similarly the ssp and fragment part is appended if provided.
    Syntax :public URI(String scheme, String ssp, String fragment)
        throws URISyntaxException
    Parameters : 
    scheme : scheme name
    ssp : scheme-specific part
    fragment : fragment part
    Throws : 
    URISyntaxException : If the URI string constructed from the given
     components violates RFC 2396
  3. Similarly other constructors are provided based on what components are known at the creation time.

  4. URI(String scheme, String userInfo, String host, int port, String path,
    String query, String fragment)

    Syntax :public URI(String scheme, String userInfo, String host, int port, 
          String path, String query, String fragment)
    Parameters :
    scheme : string representing scheme
    userInfo : userinfo of URI
    host : host component of URI
    port : listening port number
    path : path of URI
    query : String representing the query part
    fragment :optional fragment 
    
  5. URI(String scheme, String host, String path, String fragment)
    Syntax :public URI(String scheme, String host, String path, String fragment)
    Parameters :
    scheme : string representing scheme
    host : host component of URI
    path : path of URI
    fragment :optional fragment 
    
  6. URI(String scheme, String authority, String path, String query, String fragment)
    Syntax :public URI(String scheme, String authority, String path,
     String query, String fragment)
    Parameters :
    scheme : string representing scheme
    authority : authority
    path : path of URI
    query : String representing the query part
    

Methods :

  1. create() : creates a new URI object. This method can be called a pseudo constructor. It is provided for use in the situations when it is known for sure that given string will parse as the URI object and it would be considered as a programmers error if it does not parse.
    Syntax : public static URI create(String str)
    Parameters :
    str : String to be parsed as URI
  2. parseServerAuthority() : This method is used to parse the URI’s authority components if provided into user information, host and port components. This method returns a URI object whose authority field has been parsed as a server based authority.
    Syntax : public URI parseServerAuthority()
  3. normalize() : Normalizes this URI’s path. URI is constructed by normalizing the URI’s path which is consistent with RFC 2396. Returns a normalized URI object.
    Syntax : public URI normalize()
  4. resolve() : Resolves the given URI with this URI. Returns a new hierarchical URI in a manner consistent with RFC 2396.
    Syntax : public URI resolve(URI uri)
    Parameters :
    uri : URI to be resolved
    

    Another overloaded method which takes string as argument and is equivalent to calling resolve(URI.create(str)).

    Syntax : public URI resolve(String str)
    Parameters :
    str : String to be parsed as URI
  5. relativize() : Relativizes the given URI against this URI.
    Syntax : public URI relativize(URI uri)

    Parameters :
    uri : URI to relativize

  6. toURL() : Constructs a URL from this URI.
    Syntax : public URL toURL()
              throws MalformedURLException
    Throws :
    MalformedURLException : If error occurs while constructing URL
  7. getScheme() : Returns the scheme component of the URI
    Syntax : public String getScheme()
  8. getRawSchemeSpecificPart() : Returns the raw scheme specific component of the URI.
    Syntax : public String getRawSchemeSpecificPart()
  9. getSchemeSpecificPart() : Returns the decoded scheme specific component of the URI
    Syntax : public String getSchemeSpecificPart()
  10. getRawAuthority() : Returns the authority component of the URI. If the authority is server based, then further user information, host and port components are returned.
    Syntax : public String getRawAuthority()
  11. getAuthority() : Returns exact similar result as of the above method except in the decoded form.
    Syntax : public String getAuthority()
  12. getRawUserInfo() : Returns the user info component of the URI, or null if it is undefined.
    Syntax : public String getRawUserInfo()
  13. getUserInfo() : Returns the user info component of the URI in decoded form, or null if it is undefined.
    Syntax : public String getUserInfo()
  14. Java Implementation :




    // Java program to illustrate various
    // URI class methods
    import java.net.*;
      
    class uridemo1
    {
        public static void main(String[] args) throws Exception 
        {
            String uribase = "https://www.geeksforgeeks.org/";
            String urirelative = "languages/../java";
            String str = "https://www.google.co.in/?gws_rd=ssl#"+""
                    + "q=networking+in+java+geeksforgeeks"+""
                    +"&spf=1496918039682";
              
            // Constructor to create a new URI
            // by parsing the string
            URI uriBase = new URI(uribase);
      
            // create() method
            URI uri = URI.create(str);
              
            // toString() method
            System.out.println("Base URI = " + uriBase.toString());
      
            URI uriRelative = new URI(urirelative);
            System.out.println("Relative URI = " + uriRelative.toString());
      
            // resolve() method
            URI uriResolved = uriBase.resolve(uriRelative);
            System.out.println("Resolved URI = " + uriResolved.toString());
      
            // relativized() method
            URI uriRelativized = uriBase.relativize(uriResolved);
            System.out.println("Relativized URI = " + uriRelativized.toString());
      
            // normalize() method
            System.out.println(uri.normalize().toString());
      
            // getScheme() method
            System.out.println("Scheme = " + uri.getScheme());
      
            // getRawShemeSpecific() method
            System.out.println("Raw Scheme = " + uri.getRawSchemeSpecificPart());
      
            // getSchemeSpecificPart() method
            System.out.println("Scheme-specific part = " + uri.getSchemeSpecificPart());
      
            // getRawUserInfo() method
            System.out.println("Raw User Info = " + uri.getRawUserInfo());
              
            // getUserInfo() method
            System.out.println("User Info = " + uri.getUserInfo());
      
            // getAuthority() method
            System.out.println("Authority = " + uri.getAuthority());
      
            // getRawAuthority() method
            System.out.println("Raw Authority = " + uri.getRawAuthority());
      
        }
    }

    
    

    Output :

    Base URI = https://www.geeksforgeeks.org/
    Relative URI = languages/../java
    Resolved URI = https://www.geeksforgeeks.org/java
    Relativized URI = java
    https://www.google.co.in/?gws_rd=ssl#q=networking+in+
    java+geeksforgeeks&spf=1496918039682
    Scheme = https
    Raw Scheme = //www.google.co.in/?gws_rd=ssl
    Scheme-specific part = //www.google.co.in/?gws_rd=ssl
    Raw User Info = null
    User Info = null
    Authority = www.google.co.in
    Raw Authority = www.google.co.in
    
    
  15. getHost() : Returns the host component of the URI. As the host component of a URI cannot contain escaped octets, hence this method does not perform any decoding.
    Syntax : public String getHost()
  16. getPort() : Returns the port number of this URI.
    Syntax : public int getPort()
  17. getRawPath() : Returns the raw path of this URI, or null if not defined.
    Syntax : public String getRawPath()
  18. getPath() : Returns the decoded path component of this URI.
    Syntax : public String getPath()
  19. getRawQuery() : Returns the query component of the URI, or null if undefined.
    Syntax : public String getRawQuery()
  20. getQuery() : Returns the query component of the URI in decoded form, or null if undefined.
    Syntax : public String getQuery()
  21. getRawFragment() : Returns the fragment component of the URI, or null if undefined.
    Syntax : public String getRawFragment()
  22. getFragment() : Returns the decoded fragment component of this URI, or null if undefined.
    Syntax : public String getFragment()
  23. compareTo() : Compares this URI object with another URI object. Comparison by performed according to the natural ordering with String.compareTo() methods. If one component is undefined and other is defined than first is considered smaller than second. Components to be parsed are compared in their raw form rather than their encoded form.
    Syntax : public int compareTo(URI uri)
    Parameters :
    uri : URI to be compared with
  24. equals() : Tests the given object with this URI. Ig the object is not a URI, it returns false. For two URIs to be considered equal requires that either both are opaque or both are hierarchical. When checking for equality of different components, their raw form is considered rather than the encoded form.
    Syntax : public boolean equals(Object ob)
    Parameters :
    ob : object to be compared for equality
  25. isAbsolute() : Returns true if this URI is absolute, otherwise false. A URI is absolute if, and only if, it has a scheme component.
    Syntax : public boolean isAbsolute()
  26. isOpaque() : Returns true if this URI is opaque, otherwise false. A URI is opaque if, and only if, it is absolute and its scheme-specific part does not begin with a slash character (‘/’)
    Syntax : public boolean isOpaque()
  27. hashCode() : Returns the hashcode for the this URI object. All the components are taken into account while creating a hashcode for the URI object.
    Syntax : public int hashCode()
  28. toString() : Returns the string representation of this URI object.
    Syntax : public String toString()
  29. toASCIIString() : Returns the string representation in ASCII format.
    Syntax : public String toASCIIString()
  30. Java Implementation :




    //Java Program to illustrate various
    //URI class methods
    import java.net.*;
    class uridemo1 
    {
        public static void main(String[] args) throws Exception 
        {
            String str = "https://www.google.co.in/?gws_rd=ssl#"+""
                    + "q=networking+in+java+geeksforgeeks"+""
                    +"&spf=1496918039682";
      
            // Constructor to create a new URI
            // by parsing the given string.
            URI uri = new URI(str);
      
            // getHost() method
            System.out.println("Host = " + uri.getHost());
      
            // getPort() method
            System.out.println("Port = " + uri.getPath());
      
            // getRawPath() method
            System.out.println("Raw Path = " + uri.getRawPath());
      
            // getPath() method
            System.out.println("Path = " + uri.getPath());
      
            // getQuery() method
            System.out.println("Query = " + uri.getQuery());
      
            // getRawQuery() method
            System.out.println("Raw Query = " + uri.getRawQuery());
      
            // getFragment() method
            System.out.println("Fragment = " + uri.getFragment());
      
            // getRawFragment() method
            System.out.println("Raw Fragment = " + uri.getRawFragment());
      
            URI uri2 = new URI(str + "fr");
      
            // compareTo() mrthod
            System.out.println("CompareTo =" + uri.compareTo(uri2));
      
            // equals() method
            System.out.println("Equals = " + uri.equals(uri2));
      
            // hashcode() method
            System.out.println("Hashcode : " + uri.hashCode());
      
            // toString() method
            System.out.println("toString : " + uri.toString());
      
            // toASCIIString() method
            System.out.println("toASCIIString : " + uri.toASCIIString());
      
        }
    }

    
    

    Output :

    Host = www.google.co.in
    Port = /
    Raw Path = /
    Path = /
    Query = gws_rd=ssl
    Raw Query = gws_rd=ssl
    Fragment = q=networking+in+java+geeksforgeeks&spf=1496918039682
    Raw Fragment = q=networking+in+java+geeksforgeeks&spf=1496918039682
    CompareTo =-2
    Equals = false
    Hashcode : 480379574
    toString : https://www.google.co.in/?gws_rd=ssl#q=networking+
    in+java+geeksforgeeks&spf=1496918039682
    toASCIIString : https://www.google.co.in/?gws_rd=ssl#q=
    networking+in+java+geeksforgeeks&spf=1496918039682
    

References:
Official Java Documentation

ase write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads