English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java Other Topics

Java URL Handling

URL (Uniform Resource Locator) is also known as the Uniform Resource Locator in Chinese, and is sometimes俗称 as the web address. It represents resources on the Internet, such as web pages or FTP addresses.

In this chapter, we will introduce how Java handles URLs. URLs can be divided into the following parts.

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

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

The following is an example of a URL for the HTTP protocol:

http://www.oldtoolbag.com/index.html?language=cn#j2se

URL Parsing:

  • 协议为(protocol):http

  • 主机为(host:port):www.oldtoolbag.com

  • 端口号为(port): 80, the above URL example does not specify the port because the default port number for the HTTP protocol is 80。

  • 文件路径为(path):/index.html

  • 请求参数(query):language=cn

  • 定位位置(fragment):j2定位到网页中 id 属性为 j2the position of the HTML element .

URL Class Methods

The java.net package defines the URL class, which is used to handle content related to URLs. The creation and usage of the URL class will be introduced separately below.

java.net.URL provides various URL construction methods and can be used to retrieve resources.

Serial numberMethod description
1public URL(String protocol, String host, int port, String file) throws MalformedURLException.
Create a URL through the given parameters (protocol, hostname, port number, filename).
2public URL(String protocol, String host, String file) throws MalformedURLException
Create a URL using the specified protocol, hostname, and filename, and use the default port of the protocol for the port.
3public URL(String url) throws MalformedURLException
Create a URL through the given URL string
4public URL(URL context, String url) throws MalformedURLException
Create using base URL and relative URL

The URL class contains many methods for accessing various parts of a URL, the specific methods and descriptions are as follows:

Serial numberMethod description
1public String getPath()
Return the path part of the URL.
2public String getQuery()
Return the query part of the URL.
3public String getAuthority()
Get the authorization part of this URL.
4public int getPort()
Return the port part of the URL
5public int getDefaultPort()
Return the default port number of the protocol.
6public String getProtocol()
Return the protocol of the URL
7public String getHost()
Return the host of the URL
8public String getFile()
Return the file name part of the URL
9public String getRef()
Get the anchor of this URL (also known as "reference").
10public URLConnection openConnection() throws IOException
Open a URL connection and run the client to access the resource.

Online Example

The following example demonstrates how to obtain various parts of a URL using the URL class in java.net:

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

{
   public static void main(String [] args)
   {
      try
      {
         URL url = new URL("http://www.oldtoolbag.com/index.html?language=cn#j2se
         System.out.println("URL is: ") + url.toString());
         System.out.println("Protocol: ") + url.getProtocol());
         System.out.println("Verification information: ") + url.getAuthority());
         System.out.println("Filename and request parameters: ", + url.getFile());
         System.out.println("Hostname: ", + url.getHost());
         System.out.println("Path: ", + url.getPath());
         System.out.println("Port: ", + url.getPort());
         System.out.println("Default port: ", + url.getDefaultPort());
         System.out.println("Request parameters: ", + url.getQuery());
         System.out.println("Location: ", + url.getRef());
      catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}

The compiled and run results of the above examples are as follows:

URL is: http://www.oldtoolbag.com/index.html?language=cn#j2se
Protocol is: http
Verification information: www.oldtoolbag.com
Filename and request parameters:/index.html?language=cn
Hostname: www.oldtoolbag.com
Path:/index.html
Port:-1
Default port:80
Request parameters: language=cn
Location: j2se

URLConnections class methods

openConnection() returns a java.net.URLConnection.

For example:

  • If the URL you connect to is an HTTP protocol URL, the openConnection() method returns an HttpURLConnection object.

  • If the URL you connect to is a JAR file, the openConnection() method will return a JarURLConnection object.

  • etc...

The following is a list of URLConnection methods:

Serial numberMethod description
1Object getContent()
Retrieve the content of the URL link
2Object getContent(Class[] classes)
Retrieve the content of the URL link
3String getContentEncoding()
Return header content-encoding field value.
4int getContentLength()
Return header content-length field value
5String getContentType()
Return header content-type field value
6int getLastModified()
Returns the value of the header last-The value of the modified field.
7long getExpiration()
Returns the value of the expires field in the header.
8long getIfModifiedSince()
Returns the value of the ifModifiedSince field of the object.
9public void setDoInput(boolean input)
URL connections can be used for input and/Or output. If you plan to use the URL connection for input, set the DoInput flag to true; if not, set it to false. The default value is true.
10public void setDoOutput(boolean output)
URL connections can be used for input and/Or output. If you plan to use the URL connection for output, set the DoOutput flag to true; if not, set it to false. The default value is false.
11public InputStream getInputStream() throws IOException
Returns the input stream of the URL, used for reading resources
12public OutputStream getOutputStream() throws IOException
Returns the output stream of the URL, used for writing resources.
13public URL getURL()
Returns the URL connected by the URLConnection object

Online Example

The following example uses the HTTP protocol for the URL. The openConnection method 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.oldtoolbag.com");
         URLConnection urlConnection = url.openConnection();
         HttpURLConnection connection = null;
         if(urlConnection instanceof HttpURLConnection)
         {
            connection = (HttpURLConnection) urlConnection;
         }
         else
         {
            System.out.println("Please enter URL address");
            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 compilation and execution results of the above examples are as follows:

$ javac URLConnDemo.java 
$ java URLConnDemo
...Here will output the homepage of the basic tutorial website (http://www.oldtoolbag.com) HTML Content...