In this example, we will obtain many ways to get properties of a URL object, such as getProtocol(), getHost(), getPort(), getQuery(), getRef(), and so on.
Source Code
package com.beginner.examples;
import java.net.URL;
public class GetURLProperties {
public static void main(String[] args) {
//Indicates a URL reference
URL url = null;
try {
//Assign a value to this reference
url = new URL("http://www.google.cn:80?query=ok#header");
} catch (Exception e) {
e.printStackTrace();
}
//Get some properties of the URL
String protocol = url.getProtocol();
String host = url.getHost();
int port = url.getPort();
String query = url.getQuery();
String reference = url.getRef();
System.out.println("Protocol: " + protocol +
"nHost: " + host +
"nPort: " + port +
"nQuery: " + query +
"nReference: " + reference);
}
}
Output:
Protocol: http
Host: www.google.cn
Port: 80
Query: query=ok
Reference: header
References
Imported packages in Java documentation: