ParseUrlOnline
Visualize, edit, analyze and compare URLs
Visualize, edit, analyze and compare URLs
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:
import java.net.URL;
URL url = new URL("https://example.com/path?name=value#hash");
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
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}
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.