How to Parse a URL in Java?

Parsing a URL in Java is straightforward with the URL class provided in the java.net package. Here's a step-by-step guide on how to do it:

  1. Importing the URL Class
import java.net.URL;
  1. Creating a URL Object
URL url = new URL("https://example.com/path?name=value#hash");
  1. Accessing URL Components
System.out.println(url.getProtocol());  // Output: https
System.out.println(url.getHost());      // Output: example.com
System.out.println(url.getPath());      // Output: /path
System.out.println(url.getQuery());     // Output: name=value
System.out.println(url.getRef());       // Output: hash
  1. Working with URL Parameters
import java.util.Map;
import java.util.Scanner;

// Split the query string into a map of parameters
String query = url.getQuery();
Map<String, String> params = new Scanner(query.replace("&", "\n")).useDelimiter("=").tokens()
    .collect(Collectors.toMap(token -> token, token -> new Scanner(token).next()));

System.out.println(params);  // Output: {name=value}
  1. Modifying and Reconstructing URLs
import java.net.URI;

// Create a new URI with modified components
URI newUri = new URI(url.getProtocol(), null, url.getHost(), url.getPort(), "/newpath", url.getQuery(), url.getRef());
URL newUrl = newUri.toURL();

System.out.println(newUrl);  // Output: https://example.com/newpath?name=value#hash

With the URL and URI classes, parsing a URL in Java is simple, allowing you to access, analyze, and modify URLs with ease.

Lastly, if you want to grab query parameters from any url without using java, use parseurlonline.com to quickly get the data.