Java URL Handling

URL (Uniform Resource Locator), also known as a web address, represents resources on the Internet, such as web pages or FTP addresses.

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

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

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

An example of an HTTP protocol URL is as follows:

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

URL parsing:

  • Protocol:http
  • Host (host:port):www.example.com
  • Port number:80. The above URL example does not specify a port, because the default port number for the HTTP protocol is 80.
  • File path (path):/index.html
  • Query parameters (query):language=cn
  • Fragment (fragment):j2se, locating the position of the HTML element with the id attribute j2se in the web page.

URL Class Methods

The URL class is defined in the java.net package, and it is used to handle URL-related content. The creation and use of the URL class are introduced separately below.

java.net.URL provides various ways to construct URLs, and resources can be obtained through java.net.URL.

No.Method description
1public URL(String protocol, String host, int port, String file) throws MalformedURLException.
Creates a URL using the given parameters (protocol, host name, port number, file name).
2public URL(String protocol, String host, String file) throws MalformedURLException
Creates a URL using the specified protocol, host name, and file name, using the protocol's default port.
3public URL(String url) throws MalformedURLException
Creates a URL from the given URL string.
4public URL(URL context, String url) throws MalformedURLException
Creates using a base address and a relative URL.

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

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

Example

The above example demonstrates using the URL class of java.net to obtain various part parameters 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.example.com/index.html?language=cn#j2se"); System.out.println("URL:" + url.toString()); System.out.println("Protocol:" + url.getProtocol()); System.out.println("Authority:" + url.getAuthority()); System.out.println("File name and request parameters:" + url.getFile()); System.out.println("Host name:" + 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("Fragment:" + url.getRef()); }catch(IOException e) { e.printStackTrace(); } } }

The compilation and running result of the above example is as follows:

URL 为:http://www.example.com/index.html?language=cn#j2se
协议为:http
验证信息:www.example.com
文件名及请求参数:/index.html?language=cn
主机名:www.example.com
路径:/index.html
端口:-1
默认端口:80
请求参数:language=cn
定位位置:j2se

URLConnections Class Methods

openConnection() returns a java.net.URLConnection.

For example:

  • If you connect to a URL with the HTTP protocol, 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.

  • And so on...

The URLConnection method list is as follows:

No.Method description
1Object getContent()
Retrieves the content of the URL link.
2Object getContent(Class[] classes)
Retrieves the content of the URL link.
3String getContentEncoding()
Returns the value of the content-encoding header field.
4int getContentLength()
Returns the value of the content-length header field.
5String getContentType()
Returns the value of the content-type header field.
6int getLastModified()
Returns the value of the last-modified header field.
7long getExpiration()
Returns the value of the expires header field.
8long getIfModifiedSince()
Returns the value of the object's ifModifiedSince field.
9public void setDoInput(boolean input)
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 you do not intend to use it, set it to false. The default value is true.
10public void setDoOutput(boolean output)
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 you do not intend to use it, set it to false. The default value is false.
11public InputStream getInputStream() throws IOException
Returns the input stream of the URL, used to read resources.
12public OutputStream getOutputStream() throws IOException
Returns the output stream of the URL, used to write resources.
13public URL getURL()
Returns the URL connected to by the URLConnection object.

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.example.com"); URLConnection urlConnection = url.openConnection(); HttpURLConnection connection = null; if(urlConnection instanceof HttpURLConnection) { connection = (HttpURLConnection) urlConnection; } else { System.out.println("Please enter a 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 running result of the above example is as follows:

$ javac URLConnDemo.java 
$ java URLConnDemo
.....这里会输出Example首页(http://www.example.com)的 HTML 内容.....
Other extensions