import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
try {
String urlStr = "https://www.collectivesolver.com:8080/path/to/resource?query=array#fragment";
URI uri = new URI(urlStr);
String scheme = uri.getScheme();
String host = uri.getHost();
int port = uri.getPort();
String path = uri.getPath();
String fragment = uri.getFragment();
System.out.println("Scheme: " + scheme);
System.out.println("Host: " + host);
System.out.println("Port: " + port);
System.out.println("Path: " + path);
System.out.println("Fragment: " + fragment);
String query = uri.getQuery();
if (query != null) {
System.out.println("Query: " + query);
Map<String, String> params = Arrays.stream(query.split("&"))
.map(s -> s.split("=", 2)) // Limit split to 2 parts (key and value)
.filter(parts -> parts.length >= 1) // Ensure at least a key exists
.collect(Collectors.toMap(
parts -> URLDecoder.decode(parts[0], StandardCharsets.UTF_8),
parts -> parts.length > 1 ? URLDecoder.decode(parts[1], StandardCharsets.UTF_8) : null, // Handle missing value
(oldValue, newValue) -> newValue // Handle duplicate keys (choose last value)
));
params.forEach((key, value) -> System.out.println("Parameter: " + key + " = " + value));
}
} catch (URISyntaxException e) {
System.out.println("The URI is malformed: " + e.getMessage());
}
}
}
/*
run:
Scheme: https
Host: www.collectivesolver.com
Port: 8080
Path: /path/to/resource
Fragment: fragment
Query: query=array
Parameter: query = array
*/