Parse a URI String into Name-Value Collection

前端 未结 19 2477
难免孤独
难免孤独 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 01:59

    Java 8 one statement

    Given the URL to analyse:

    URL url = new URL("https://google.com.ua/oauth/authorize?client_id=SS&response_type=code&scope=N_FULL&access_type=offline&redirect_uri=http://localhost/Callback");
    

    This solution collects a list of pairs:

    List> list = 
            Pattern.compile("&").splitAsStream(url.getQuery())
            .map(s -> Arrays.copyOf(s.split("="), 2))
            .map(o -> new AbstractMap.SimpleEntry(decode(o[0]), decode(o[1])))
            .collect(toList());
    

    This solution on the other hand collects a map (given that in a url there can be more parameters with same name but different values).

    Map> list = 
            Pattern.compile("&").splitAsStream(url.getQuery())
            .map(s -> Arrays.copyOf(s.split("="), 2))
            .collect(groupingBy(s -> decode(s[0]), mapping(s -> decode(s[1]), toList())));
    

    Both the solutions must use an utility function to properly decode the parameters.

    private static String decode(final String encoded) {
        try {
            return encoded == null ? null : URLDecoder.decode(encoded, "UTF-8");
        } catch(final UnsupportedEncodingException e) {
            throw new RuntimeException("Impossible: UTF-8 is a required encoding", e);
        }
    }
    

提交回复
热议问题