Parse a URI String into Name-Value Collection

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

    Using above mentioned comments and solutions, I am storing all the query parameters using Map where Objects either can be string or Set. The solution is given below. It is recommended to use some kind of url validator to validate the url first and then call convertQueryStringToMap method.

    private static final String DEFAULT_ENCODING_SCHEME = "UTF-8";
    
    public static Map convertQueryStringToMap(String url) throws UnsupportedEncodingException, URISyntaxException {
        List params = URLEncodedUtils.parse(new URI(url), DEFAULT_ENCODING_SCHEME);
        Map queryStringMap = new HashMap<>();
        for(NameValuePair param : params){
            queryStringMap.put(param.getName(), handleMultiValuedQueryParam(queryStringMap, param.getName(), param.getValue()));
        }
        return queryStringMap;
    }
    
    private static Object handleMultiValuedQueryParam(Map responseMap, String key, String value) {
        if (!responseMap.containsKey(key)) {
            return value.contains(",") ? new HashSet(Arrays.asList(value.split(","))) : value;
        } else {
            Set queryValueSet = responseMap.get(key) instanceof Set ? (Set) responseMap.get(key) : new HashSet();
            if (value.contains(",")) {
                queryValueSet.addAll(Arrays.asList(value.split(",")));
            } else {
                queryValueSet.add(value);
            }
            return queryValueSet;
        }
    }
    

提交回复
热议问题