Easy Tutorial
❮ Character Tolowercase Number Parseint ❯

Java URL Handling

URL (Uniform Resource Locator), also known as a web address, is a reference to a resource on the Internet. It indicates the location of a resource, such as a web page or an FTP address.

This section will introduce how Java handles URLs. A URL can be broken down into the following parts:

protocol://host:port/path?query#fragment

The protocol can be HTTP, HTTPS, FTP, or File. The port is the port number, and the path is the file path and file name.

An example of an HTTP protocol URL is:

http://www.tutorialpro.org/index.html?language=cn#j2se

URL Parsing:


URL Class Methods

The URL class is defined in the java.net package and is used to handle URL-related content. Below, we will introduce the creation and usage of the URL class.

java.net.URL provides various ways to construct URLs and allows access to resources through java.net.URL.

No. Method Description
1 public URL(String protocol, String host, int port, String file) throws MalformedURLException. <br>Creates a URL from the given parameters (protocol, host, port, file).
2 public URL(String protocol, String host, String file) throws MalformedURLException <br>Creates a URL with the specified protocol, host, and file, using the default port for the protocol.
3 public URL(String url) throws MalformedURLException <br>Creates a URL from the given URL string.
4 public URL(URL context, String url) throws MalformedURLException <br>Creates a URL using a base address and a relative URL.

The URL class contains many methods for accessing different parts of the URL, as described below:

No. Method Description
1 public String getPath() <br>Returns the path part of the URL.
2 public String getQuery() <br>Returns the query part of the URL.
3 public String getAuthority() <br>Returns the authority part of the URL.
4 public int getPort() <br>Returns the port part of the URL.
5 public int getDefaultPort() <br>Returns the default port number for the protocol.
6 public String getProtocol() <br>Returns the protocol of the URL.
7 public String getHost() <br>Returns the host of the URL.
8 public String getFile() <br>Returns the file part of the URL.
9 public String getRef() <br>Returns the anchor (also known as "reference") of the URL.
10 public URLConnection openConnection() throws IOException <br>Opens a URL connection and allows the client to access the resource.

Example

The following example demonstrates how to use the java.net.URL class to retrieve various parts of a URL:

URLDemo.java

import java.net.*;
import java.io.*;

public class URLDemo
{
   public static void main(String [] args)
   {
      try
      {
         URL url = new URL("http://www.tutorialpro.org/index.html?language=cn#j2se");
```java
System.out.println("URL is: " + url.toString());
System.out.println("Protocol is: " + url.getProtocol());
System.out.println("Authority is: " + url.getAuthority());
System.out.println("File name and request parameters are: " + url.getFile());
System.out.println("Host is: " + url.getHost());
System.out.println("Path is: " + url.getPath());
System.out.println("Port is: " + url.getPort());
System.out.println("Default port is: " + url.getDefaultPort());
System.out.println("Request parameters are: " + url.getQuery());
System.out.println("Reference is: " + url.getRef());
} catch(IOException e) {
   e.printStackTrace();
}
}

The above example compiles and runs with the following result:

URL is: http://www.tutorialpro.org/index.html?language=cn#j2se
Protocol is: http
Authority is: www.tutorialpro.org
File name and request parameters are: /index.html?language=cn
Host is: www.tutorialpro.org
Path is: /index.html
Port is: -1
Default port is: 80
Request parameters are: language=cn
Reference is: j2se

URLConnections Class Methods

openConnection() returns a java.net.URLConnection.

For example:

Here is a list of URLConnection methods:

No. Method Description
1 Object getContent() <br>Retrieves the content of the URL connection.
2 Object getContent(Class[] classes) <br>Retrieves the content of the URL connection.
3 String getContentEncoding() <br>Returns the value of the content-encoding header field.
4 int getContentLength() <br>Returns the value of the content-length header field.
5 String getContentType() <br>Returns the value of the content-type header field.
6 int getLastModified() <br>Returns the value of the last-modified header field.
7 long getExpiration() <br>Returns the value of the expires header field.
8 long getIfModifiedSince() <br>Returns the value of the ifModifiedSince field of the object.
9 public void setDoInput(boolean input) <br>A URL connection can be used for input and/or output. If you intend to use the URL connection for input, set the DoInput flag to true; if not, set it to false. The default value is true.
10 public void setDoOutput(boolean output) <br>A URL connection can be used for input and/or output. If you intend to use the URL connection for output, set the DoOutput flag to true; if not, set it to false. The default value is false.
11 public InputStream getInputStream() throws IOException <br>Returns an input stream that reads from this open connection.
12 public OutputStream getOutputStream() throws IOException <br>Returns an output stream that writes to this open connection.
| 13 | public URL getURL() <br>Returns the URL to which the URLConnection object is connected |

### Example

In the following example, the URL uses the HTTP protocol. openConnection returns an HttpURLConnection object.

## URLConnDemo.java

import java.net.; import java.io.; public class URLConnDemo { public static void main(String [] args) { try { URL url = new URL("http://www.tutorialpro.org"); URLConnection urlConnection = url.openConnection(); HttpURLConnection connection = null; if(urlConnection instanceof HttpURLConnection) { connection = (HttpURLConnection) urlConnection; } else { System.out.println("Please enter an HTTP URL."); return; } BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); String urlString = ""; String current; while((current = in.readLine()) != null) { urlString += current; } System.out.println(urlString); }catch(IOException e) { e.printStackTrace(); } } }


The above example compiles and runs as follows:

$ javac URLConnDemo.java $ java URLConnDemo .....This will output the HTML content of the homepage of tutorialpro.org (http://www.tutorialpro.org)..... ```

❮ Character Tolowercase Number Parseint ❯