How to use the URI class in a Java program. - Java Network

Java examples for Network:URI

Description

How to use the URI class in a Java program.

Demo Code

import java.net.URI;
import java.net.URISyntaxException;

public class Main {
  public static void main(String[] args) {
    String baseURIStr = "http://www.java2s.com/fake.html?" +
                        "id=999&rate=1.5%25#foo";
    String relativeURIStr = "../folder/welcome.html";

    try {/*from w  ww  .j  a v a  2s . c o  m*/
      URI baseURI = new URI(baseURIStr);
      URI relativeURI = new URI(relativeURIStr);

      // Resolve the relative URI with respect to the base URI
      URI resolvedURI = baseURI.resolve(relativeURI);

      printURIDetails(baseURI);
      printURIDetails(relativeURI);
      printURIDetails(resolvedURI);
    }
    catch (URISyntaxException e) {
      e.printStackTrace();
    }
  }

  public static void printURIDetails(URI uri) {
    System.out.println("URI:" + uri);
    System.out.println("Normalized:" + uri.normalize());
    String parts = "[Scheme=" + uri.getScheme() +
                   ", Authority=" + uri.getAuthority() +
                   ", Path=" + uri.getPath() +
                   ", Query:" + uri.getQuery() +
                   ", Fragment:" + uri.getFragment() + "]";

    System.out.println(parts);
    System.out.println();
  }
}

Related Tutorials