Analizar una cadena URI en una colección de nombre-valor

Resuelto Sergey Shafiev asked hace 11 años • 34 respuestas

Tengo el URI así:

https://google.com.ua/oauth/authorize?client_id=SS&response_type=code&scope=N_FULL&access_type=offline&redirect_uri=http://localhost/Callback

Necesito una colección con elementos analizados:

NAME               VALUE
------------------------
client_id          SS
response_type      code
scope              N_FULL
access_type        offline
redirect_uri       http://localhost/Callback

Para ser exactos, necesito un equivalente de Java para el HttpUtility.ParseQueryStringmétodo C#/.NET.

Sergey Shafiev avatar Nov 28 '12 03:11 Sergey Shafiev
Aceptado

Si está buscando una manera de lograrlo sin utilizar una biblioteca externa, el siguiente código le ayudará.

public static Map<String, String> splitQuery(URL url) throws UnsupportedEncodingException {
    Map<String, String> query_pairs = new LinkedHashMap<String, String>();
    String query = url.getQuery();
    String[] pairs = query.split("&");
    for (String pair : pairs) {
        int idx = pair.indexOf("=");
        query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
    }
    return query_pairs;
}

Puede acceder al mapa devuelto usando <map>.get("client_id"), con la URL proporcionada en su pregunta, esto devolvería "SS".

ACTUALIZAR URL-Decodificación agregada

ACTUALIZACIÓN Como esta respuesta sigue siendo bastante popular, hice una versión mejorada del método anterior, que maneja múltiples parámetros con la misma clave y también parámetros sin valor.

public static Map<String, List<String>> splitQuery(URL url) throws UnsupportedEncodingException {
  final Map<String, List<String>> query_pairs = new LinkedHashMap<String, List<String>>();
  final String[] pairs = url.getQuery().split("&");
  for (String pair : pairs) {
    final int idx = pair.indexOf("=");
    final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
    if (!query_pairs.containsKey(key)) {
      query_pairs.put(key, new LinkedList<String>());
    }
    final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
    query_pairs.get(key).add(value);
  }
  return query_pairs;
}

ACTUALIZAR la versión Java8

public Map<String, List<String>> splitQuery(URL url) {
    if (Strings.isNullOrEmpty(url.getQuery())) {
        return Collections.emptyMap();
    }
    return Arrays.stream(url.getQuery().split("&"))
            .map(this::splitQueryParameter)
            .collect(Collectors.groupingBy(SimpleImmutableEntry::getKey, LinkedHashMap::new, mapping(Map.Entry::getValue, toList())));
}

public SimpleImmutableEntry<String, String> splitQueryParameter(String it) {
    final int idx = it.indexOf("=");
    final String key = idx > 0 ? it.substring(0, idx) : it;
    final String value = idx > 0 && it.length() > idx + 1 ? it.substring(idx + 1) : null;
    return new SimpleImmutableEntry<>(
        URLDecoder.decode(key, StandardCharsets.UTF_8),
        URLDecoder.decode(value, StandardCharsets.UTF_8)
    );
}

Ejecutando el método anterior con la URL

https://stackoverflow.com?param1=value1&param2=&param3=value3&param3

devuelve este mapa:

{param1=["value1"], param2=[null], param3=["value3", null]}
Pr0gr4mm3r avatar Nov 27 '2012 20:11 Pr0gr4mm3r

org.apache.http.client.utils.URLEncodedUtils

es una biblioteca muy conocida que puede hacerlo por usted

import org.apache.hc.client5.http.utils.URLEncodedUtils

String url = "http://www.example.com/something.html?one=1&two=2&three=3&three=3a";

List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), Charset.forName("UTF-8"));

for (NameValuePair param : params) {
  System.out.println(param.getName() + " : " + param.getValue());
}

Salidas

one : 1
two : 2
three : 3
three : 3a
Ruan Mendes avatar Nov 27 '2012 20:11 Ruan Mendes