Parse a URI String into Name-Value Collection

前端 未结 19 2525
难免孤独
难免孤独 2020-11-22 01:34

I\'ve got the URI like this:

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


        
19条回答
  •  臣服心动
    2020-11-22 02:03

    If you are looking for a way to achieve it without using an external library, the following code will help you.

    public static Map splitQuery(URL url) throws UnsupportedEncodingException {
        Map query_pairs = new LinkedHashMap();
        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;
    }
    

    You can access the returned Map using .get("client_id"), with the URL given in your question this would return "SS".

    UPDATE URL-Decoding added

    UPDATE As this answer is still quite popular, I made an improved version of the method above, which handles multiple parameters with the same key and parameters with no value as well.

    public static Map> splitQuery(URL url) throws UnsupportedEncodingException {
      final Map> query_pairs = new LinkedHashMap>();
      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());
        }
        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;
    }
    

    UPDATE Java8 version

    public Map> 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 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, "UTF-8"),
            URLDecoder.decode(value, "UTF-8")
        );
    }
    

    Running the above method with the URL

    https://stackoverflow.com?param1=value1¶m2=¶m3=value3¶m3

    returns this Map:

    {param1=["value1"], param2=[null], param3=["value3", null]}
    

提交回复
热议问题