Classe Java.net.URI a Java

Aquesta classe proporciona mètodes per crear instàncies d'URI a partir dels seus components o analitzant la forma de cadena d'aquests components per accedir i recuperar diferents components d'una instància d'URI. Què és l'URI? URI significa Uniform Resource Identifier. Un identificador uniforme de recurs és una seqüència de caràcters que s'utilitza per identificar un recurs concret. Permet la interacció de la representació del recurs a través de la xarxa mitjançant protocols específics.

URI URL i URN: quina és la diferència?

La pregunta que us ha de venir al cap ha de ser que si l'URI identifica un recurs, què fa l'URL? La gent sovint utilitza els termes de manera intercanviable, però no és correcte. Segons 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/java/java//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. Sintaxi URI:
scheme:[//[user:password@]host[:port]][/]path[?query][#fragment] 
    esquema: 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:[email protected]:1234/path/data ?key=value&key2=value2#fragid1 
    autoritat: 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:[email protected]:1234  /path/data ?key=value&key2=value2#fragid1 
    camí: The path represents a string containing the address within the server to the resource.
    abc://admin:[email protected]:1234/  path/data   ?key=value&key2=value2#fragid1 
    consulta: 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:[email protected]:1234/path/data   ?key=value&key2=value2  #fragid1 
    fragment: Fragments are used to identify secondary resources as headings or subheadings within a page etc.
    abc://admin:[email protected]:1234/path/data ?key=value&key2=value2  #fragid1   
Constructors:
    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 
    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 
    De la mateixa manera, es proporcionen altres constructors en funció dels components coneguts en el moment de la creació. 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  
    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  
    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  
Mètodes:
    crear(): 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 
    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() 
    normalitzar(): 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() 
    resoldre(): 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 
    relativitzar(): Relativizes the given URI against this URI.
      Syntax :   public URI relativize(URI uri) 
    Paràmetres: uri : URI per relativitzar toURL(): Constructs a URL from this URI.
      Syntax :   public URL toURL() throws MalformedURLException   Throws :   MalformedURLException : If error occurs while constructing URL 
    getScheme(): Returns the scheme component of the URI
      Syntax :   public String getScheme() 
    getRawSchemeSpecificPart(): Returns the raw scheme specific component of the URI.
      Syntax :   public String getRawSchemeSpecificPart() 
    getSchemeSpecificPart(): Returns the decoded scheme specific component of the URI
      Syntax :   public String getSchemeSpecificPart() 
    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() 
    getAuthority(): Returns exact similar result as of the above method except in the decoded form.
      Syntax :   public String getAuthority() 
    getRawUserInfo(): Returns the user info component of the URI or null if it is undefined.
      Syntax :   public String getRawUserInfo() 
    getUserInfo(): Returns the user info component of the URI in decoded form or null if it is undefined.
      Syntax :   public String getUserInfo() 
    Implementació Java: Java
       // 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  ());      }   }   
    Sortida:
    Base URI = https://www.geeksforgeeks.org/ Relative URI = languages/../java Resolved URI = https://www.geeksforgeeks.org/java/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  
    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() 
    getPort(): Returns the port number of this URI.
      Syntax :   public int getPort() 
    Getrawpath (): Returns the raw path of this URI or null if not defined.
      Syntax :   public String getRawPath() 
    getPath(): Returns the decoded path component of this URI.
      Syntax :   public String getPath() 
    getRawQuery(): Returns the query component of the URI or null if undefined.
      Syntax :   public String getRawQuery() 
    getQuery(): Returns the query component of the URI in decoded form or null if undefined.
      Syntax :   public String getQuery() 
    getRawFragment(): Returns the fragment component of the URI or null if undefined.
      Syntax :   public String getRawFragment() 
    getFragment(): Returns the decoded fragment component of this URI or null if undefined.
      Syntax :   public String getFragment() 
    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 
    és igual a (): 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 
    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() 
    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() 
    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() 
    toString(): Returns the string representation of this URI object.
      Syntax :   public String toString() 
    toASCIIString(): Returns the string representation in ASCII format.
      Syntax :   public String toASCIIString() 
    Implementació Java : Java
       //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  ());      }   }   
    Sortida:
    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  
Referències: Documentació oficial de Java escriviu comentaris si trobeu alguna cosa incorrecta o voleu compartir més informació sobre el tema tractat anteriorment. Crea un qüestionari