Parsing a URL using the built-in URL class methods. - Java Network

Java examples for Network:URL

Introduction

Accessor Methods for Querying URLs

Method URL Information Returned
getAuthority() Authority component
getFile() File name component
getHost() Hostname component
getPath() Path component
getProtocol() Protocol identifier component
getRef()Reference component
getQuery() Query component

Demo Code


import java.io.IOException;
import java.net.URL;

public class Main {
  public static void main(String[] args) {
    URL url1 = null;/*www .j  a  va2 s .co m*/
    URL url2 = null;
    try {
      url1 = new URL("http://www.java2s.com/a/r/?q=javafx");

      String host = url1.getHost();
      String path = url1.getPath();
      String query = url1.getQuery();
      String protocol = url1.getProtocol();
      String authority = url1.getAuthority();
      String ref = url1.getRef();

      System.out.println("The URL " + url1.toString()
          + " parses to the following:\n");
      System.out.println("Host: " + host + "\n");
      System.out.println("Path: " + path + "\n");
      System.out.println("Query: " + query + "\n");
      System.out.println("Protocol: " + protocol + "\n");
      System.out.println("Authority: " + authority + "\n");
      System.out.println("Reference: " + ref + "\n");

      url2 = new URL(protocol + "://" + host + path + "?q=java");

    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}

Related Tutorials