Java Network Tutorial - Java URL








An absolute URI has the following generic format:

scheme:scheme-specific-part

The scheme-specific-part depends on the scheme.

For example, an http scheme uses one format, and a mailto scheme uses another format.

Another generic form of a URI is as follows and it represents a URL.

scheme://<authority><path>?<query>#<fragment>

scheme indicates a method to access a resource.

It is the protocol name such as http, ftp, etc.

The scheme and path parts are required in a URI. All other parts are optional.

The path part may be an empty string. The authority part indicates the server name or IP address.

If the authority part represents a server name, it may be in the form of userinfo@host:port.

For example, a URL that identifies a file in a local file system uses the file scheme as file:///c:/documents/java.doc.





URL

The URI syntax uses a hierarchical syntax in its path part.

Multiple parts of the path are separated by a forward slash (/).

The query part indicates that the resource is obtained by executing the specified query.

It consists of name-value pairs separated by an ampersand &.

The name and value are separated by an equal sign =.

For example, id=123&num=5 is a query, which has two parts, id and num. The value for id is 123 and the value for num is 5.

The fragment part identifies a secondary resource, typically a subset of the primary resource identified by another part of the URI.

The following is an example of a URI, which is also broken into parts:

URI:        http://www.java2s.com/java/a.html?id=123#abc
Scheme:     http 
Authority:  www.java2s.com 
Path:       /java/a.html 
Query:      id=123
Fragment:   abc

To use a space character in a URI, use %20, which is the escaped form for a space.

Use %25 to represent a % character in a URI.

For example, to use a value of 5.2% in a query

http://www.java2s.com/details?rate=5.2%25




Java URI Class

Java represents a URI and a URL as objects.

It provides the following four classes that you can use to work with a URI and a URL as objects in a Java program:

java.net.URI
java.net.URL
java.net.URLEncoder
java.net.URLDecoder

The following code creates a URI object.

URI baseURI  = new URI("http://www.java2s.com");

To create a URI with relative URI string and resolve it using baseURI

URI baseURI  = new URI("http://www.java2s.com");
URI relativeURI = new URI("welcome.html");
URI resolvedRelativeURI = baseURI.resolve(relativeURI);

Complete Code

import java.net.URI;
/*from ww w .  j a  v a2  s  .c  om*/
public class Main {
  public static void main(String[] args) throws Exception {
    String baseURIStr = "http://www.java2s.com/a/b/c/index.html?id=1&rate=5%25#foo";
    String relativeURIStr = "../x/y/z/welcome.html";

    URI baseURI = new URI(baseURIStr);
    URI relativeURI = new URI(relativeURIStr);

    URI resolvedURI = baseURI.resolve(relativeURI);

    printURIDetails(baseURI);
    printURIDetails(relativeURI);
    printURIDetails(resolvedURI);
  }
  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();
  }
}

The code above generates the following result.

We can get a URL object from a URI object using its toURL() method as shown:

URL  baseURL = baseURI.toURL();

Example 2

A Sample Class That Demonstrates the Use of the java.net.URL Class

import java.net.URL;
//  w w  w  .ja  v a2 s.  c  o m
public class Main {
  public static void main(String[] args) throws Exception {
    String baseURLStr = "http://www.ietf.org/rfc/rfc3986.txt";
    String relativeURLStr = "rfc2732.txt";
    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);
  }
}

The code above generates the following result.

URLEncoder and URLDecoder

URLEncoder and URLDecoder classes are used to encode and decode strings, respectively.

import java.net.URLDecoder;
import java.net.URLEncoder;
//  w w w  . j  a  v a  2  s. co m
public class Main {
  public static void main(String[] args) throws Exception {
    String source = "index&^%*a test for 2.5% and  &";
    String encoded = URLEncoder.encode(source, "utf-8");
    String decoded = URLDecoder.decode(encoded, "utf-8");
    System.out.println("Source: " + source);
    System.out.println("Encoded: " + encoded);
    System.out.println("Decoded: " + decoded);

  }
}

The code above generates the following result.

Example 3

Accessing the Contents of a URL

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
//from w  w  w .j a v  a2  s  .  co m
public class Main {
  public static String getURLContent(String urlStr) throws Exception {
    BufferedReader br = null;
    URL url = new URL(urlStr);
    InputStream ins = url.openStream();
    br = new BufferedReader(new InputStreamReader(ins));

    StringBuilder sb = new StringBuilder();
    String msg = null;
    while ((msg = br.readLine()) != null) {
      sb.append(msg);
      sb.append("\n"); // Append a new line
    }
    br.close();
    return sb.toString();
  }

  public static void main(String[] args) throws Exception {
    String urlStr = "http://java2s.com";
    String content = getURLContent(urlStr);
    System.out.println(content);
  }
}

The code above generates the following result.

Example 4

A URL Reader/Writer Class That Writes/Reads Data to/from a URL.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
/* w w w.j  a  v  a2  s.  c o  m*/
public class Main {
  public static String getURLContent(String urlStr)
      throws Exception {
    URL url = new URL(urlStr);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    connection.connect();
    OutputStream ous = connection.getOutputStream();
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(ous));
    bw.write("index.htm");
    bw.flush();
    bw.close();

    printRequestHeaders(connection);
    InputStream ins = connection.getInputStream();

    BufferedReader br = new BufferedReader(new InputStreamReader(ins));
    StringBuffer sb = new StringBuffer();
    String msg = null;
    while ((msg = br.readLine()) != null) {
      sb.append(msg);
      sb.append("\n"); // Append a new line
    }
    br.close();
    return sb.toString();
  }
  public static void printRequestHeaders(URLConnection connection) {
    Map headers = connection.getHeaderFields();
    System.out.println(headers);
  }
  public static void main(String[] args) throws Exception {
    String urlStr = "http://www.java2s.com";
    String content = getURLContent(urlStr);
    System.out.println(content);
  }
}

The code above generates the following result.

Jar URLConnection

The following code shows how to get a JarURLConnection object.

To use its methods to get the JAR specific data.

String str = "jar:http://yoursite.com/my.jar!/my/Abc.class"; 
URL  url = new URL(str);
JarURLConnection  connection = (JarURLConnection)url.openConnection();