Url Parsing in Logo

Here’s the translation of the Go URL parsing example to Java, formatted in Markdown for Hugo:

Our URL parsing program demonstrates how to parse and extract various components from a URL string in Java.

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

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.
            String userInfo = uri.getUserInfo();
            System.out.println(userInfo);
            if (userInfo != null) {
                String[] userParts = userInfo.split(":");
                System.out.println(userParts[0]);
                if (userParts.length > 1) {
                    System.out.println(userParts[1]);
                }
            }

            // The Host contains both the hostname and the port,
            // if present.
            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 using a custom function.
            System.out.println(uri.getRawQuery());
            Map<String, String> queryParams = parseQuery(uri.getQuery());
            System.out.println(queryParams);
            System.out.println(queryParams.get("k"));

        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    // A simple method to parse query parameters into a map.
    private static Map<String, String> parseQuery(String query) {
        Map<String, String> queryPairs = new LinkedHashMap<>();
        if (query != null) {
            String[] pairs = query.split("&");
            for (String pair : pairs) {
                int idx = pair.indexOf("=");
                queryPairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"),
                               URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
            }
        }
        return queryPairs;
    }
}

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
/path
f
k=v
{k=v}
v

In this Java version:

  1. We use the URI class from java.net package to parse the URL.
  2. The getScheme(), getHost(), getPort(), getPath(), getFragment(), and getRawQuery() methods are used to extract different parts of the URL.
  3. For parsing user information, we need to split the getUserInfo() result manually.
  4. Java doesn’t provide a built-in method to parse query parameters into a map, so we’ve implemented a simple parseQuery method to do this.
  5. We use a try-catch block to handle potential URISyntaxException.

This example demonstrates how to work with URLs in Java, showing how to extract various components such as scheme, user info, host, port, path, query parameters, and fragments.