Url Parsing in CLIPS
Our URL parsing program demonstrates how to parse and extract information from a URL string in Java.
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class URLParsing {
public static void main(String[] args) {
// We'll parse this example URL, which includes a
// scheme, authentication info, host, port, path,
// query params, and query fragment.
String s = "postgres://user:pass@host.com:5432/path?k=v#f";
try {
// Parse the URL and ensure there are no errors.
URI uri = new URI(s);
// Accessing the scheme is straightforward.
System.out.println(uri.getScheme());
// UserInfo contains all authentication info; we need to split it
// to get individual username and password.
System.out.println(uri.getUserInfo());
String[] userInfo = uri.getUserInfo().split(":");
System.out.println(userInfo[0]);
System.out.println(userInfo[1]);
// The Host contains both the hostname and the port,
// if present. We can access them separately.
System.out.println(uri.getHost() + ":" + uri.getPort());
System.out.println(uri.getHost());
System.out.println(uri.getPort());
// Here we extract the path and the fragment after the #.
System.out.println(uri.getPath());
System.out.println(uri.getFragment());
// To get query params in a string of k=v format,
// use getRawQuery(). You can also parse query params
// into a map.
System.out.println(uri.getRawQuery());
Map<String, String> queryParams = Arrays.stream(uri.getQuery().split("&"))
.map(param -> param.split("="))
.collect(Collectors.toMap(param -> param[0], param -> param[1]));
System.out.println(queryParams);
System.out.println(queryParams.get("k"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
Running our URL parsing program shows all the different pieces that we extracted.
$ javac URLParsing.java
$ java URLParsing
postgres
user:pass
user
pass
host.com:5432
host.com
5432
/path
f
k=v
{k=v}
v
This Java program uses the java.net.URI
class to parse the URL. It provides methods to access various components of the URL. For query parameter parsing, we use Java 8 streams to split the query string and create a map.
Note that Java’s URI
class handles the parsing slightly differently from Go’s url.Parse()
. For example, it doesn’t provide a direct method to get the password, so we split the UserInfo string manually. Also, the query parameters are handled as a single string by default, so we implement custom parsing for demonstration purposes.