Parse a URI String into Name-Value Collection

前端 未结 19 2889
难免孤独
难免孤独 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:56

    If you're using Java 8 and you're willing to write a few reusable methods, you can do it in one line.

    private Map> parse(final String query) {
        return Arrays.asList(query.split("&")).stream().map(p -> p.split("=")).collect(Collectors.toMap(s -> decode(index(s, 0)), s -> Arrays.asList(decode(index(s, 1))), this::mergeLists));
    }
    
    private  List mergeLists(final List l1, final List l2) {
        List list = new ArrayList<>();
        list.addAll(l1);
        list.addAll(l2);
        return list;
    }
    
    private static  T index(final T[] array, final int index) {
        return index >= array.length ? null : array[index];
    }
    
    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);
        }
    }
    

    But that's a pretty brutal line.

提交回复
热议问题