Parse a URI String into Name-Value Collection in java

Parse a URI String into Name-Value Collection in java

To parse a URI string into a name-value collection in Java, you can use the java.net.URI class to parse the URI, and then extract the components (such as query parameters) and store them in a collection. One common choice for storing name-value pairs is a Map like HashMap or LinkedHashMap. Here's a step-by-step example:

import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; public class URIParsingExample { public static void main(String[] args) { try { // Create a URI from a string URI uri = new URI("https://example.com/path?param1=value1&param2=value2"); // Extract query parameters from the URI String query = uri.getQuery(); // Create a map to store the name-value pairs Map<String, String> paramMap = new HashMap<>(); // Check if the query is not null or empty if (query != null && !query.isEmpty()) { // Split the query string into individual parameter pairs String[] params = query.split("&"); // Iterate through the parameter pairs and store them in the map for (String param : params) { String[] keyValue = param.split("="); if (keyValue.length == 2) { String key = keyValue[0]; String value = keyValue[1]; paramMap.put(key, value); } } } // Print the name-value pairs for (Map.Entry<String, String> entry : paramMap.entrySet()) { System.out.println("Name: " + entry.getKey() + ", Value: " + entry.getValue()); } } catch (URISyntaxException e) { e.printStackTrace(); } } } 

In this example:

  1. We create a URI object from a URI string.
  2. We use the getQuery() method to extract the query component from the URI, which contains the name-value pairs.
  3. We create a HashMap (paramMap) to store the extracted name-value pairs.
  4. We split the query string into individual parameter pairs using the "&" separator.
  5. We split each parameter pair into a key and a value using the "=" separator.
  6. We add each key-value pair to the paramMap.
  7. Finally, we iterate through the paramMap and print the name-value pairs.

This code will extract the query parameters from the URI and store them in a map, allowing you to access and use them as needed in your Java application.


More Tags

xml-nil dpkt data-uri textarea buffer-overflow mention gnu-coreutils vue-props gps server-sent-events

More Java Questions

More Stoichiometry Calculators

More Chemical thermodynamics Calculators

More Livestock Calculators

More Investment Calculators