Explain Codes LogoExplain Codes Logo

Parse a URI String into Name-Value Collection

java
prompt-engineering
functions
collections
Nikita BarsukovbyNikita Barsukov·Mar 2, 2025
TLDR

Extract key-value details from a URI string using Java's URI and Apache HttpClient's URLEncodedUtils:

import java.net.URI; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import java.nio.charset.StandardCharsets; import java.util.List; // ... URI uri = new URI("http://example.com/?param1=value1&param2=value2"); List<NameValuePair> queryParams = URLEncodedUtils.parse(uri, StandardCharsets.UTF_8); queryParams.forEach(param -> System.out.println(param.getName() + " : " + param.getValue()));

Dependencies: Apache HttpClient library required.
Output: Presents the URI query's key-value pairs. Bazinga!

Invoking Java 8 features for elegance

Java 8's Streams API simplifies parsing of URI query strings. It effectively means you're cool and modern:

import java.net.URI; import java.util.Map; import java.util.stream.Collectors; // ... URI uri = new URI("http://example.com/?param1=value1&param2="); Map<String, List<String>> query_pairs = URLEncodedUtils.parse(uri, StandardCharsets.UTF_8).stream() .collect(Collectors.groupingBy( NameValuePair::getName, Collectors.mapping(NameValuePair::getValue, Collectors.toList()) ));

Highlights:

  • Dealing with same keys having multiple values. Yes, it happens.
  • Stream actions for clever and readable parsing. You're doing it, Peter!

Tricky URI scenarios like a pro

Empty values or repeating keys can bring eyebrows together. Here's a strategy:

// ... Map<String, List<String>> query_pairs = new LinkedHashMap<>(); String query = uri.getQuery(); if (query != null) { for (String pair : query.split("&")) { int idx = pair.indexOf("="); query_pairs.computeIfAbsent( URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8.name()), k -> new ArrayList<>() ).add(idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8.name()) : null); } }

Key takeaways:

  • LinkedHashMap preserves parsing order. Order! Order!
  • URLDecoder handles URL encoding. Yeah, those %20s? They’re spaces!
  • A strategy for valueless parameters. Even the void can speak volumes.

Walking the path of external libraries

External libraries like Guava or Spring's UriComponentsBuilder bring elegant parsing moves with lesser effort:

// With Guava's Splitter Map<String, String> query_pairs = Splitter.on('&') .trimResults() .withKeyValueSeparator('=') .split(uri.getQuery()); // With Spring's UriComponentsBuilder MultiValueMap<String, String> params = UriComponentsBuilder.fromUriString(uri.toString()) .build() .getQueryParams();

USPs:

  • Easy syntax and high-performance.
  • Handles multiple value pairs and automatic encoding quirks. Yes! There's no more tears for encodings.

Polishing parsing strategies

Custom parsing or pre-built library?

While falling between a custom method and an external library, remember:

  • Reliability: Libraries have been bullied by more bugs than your custom method.
  • Performance: Libraries might surf through complex strings better.
  • Maintenance: Libraries keep quiet and handle edge cases, as well as updates.

Robustness testing

Test your method with diverse URIs to ensure robustness:

// Add test URIs with varying complexities String[] testUris = { "http://example.com/", "http://example.com/?param=value&empty", "http://example.com/?param1=value1&&param2=", }; // Exercise your parsing on each test URI and validate results

Mastering character encoding

Correct character encoding can prevent a promising Sunday turning into a debugging marathon:

URLEncodedUtils.parse(uri, Charset.forName("UTF-8"));

Remember:

  • UTF-8 is the fairy godmother of the web.
  • Java's StandardCharsets comes with the necessary character sets.