Parsing query strings on Android

前端 未结 25 1394
时光说笑
时光说笑 2020-11-22 17:41

Java EE has ServletRequest.getParameterValues().

On non-EE platforms, URL.getQuery() simply returns a string.

What\'s the normal way to properly parse the qu

25条回答
  •  青春惊慌失措
    2020-11-22 17:43

    Just for reference, this is what I've ended up with (based on URLEncodedUtils, and returning a Map).

    Features:

    • it accepts the query string part of the url (you can use request.getQueryString())
    • an empty query string will produce an empty Map
    • a parameter without a value (?test) will be mapped to an empty List

    Code:

    public static Map> getParameterMapOfLists(String queryString) {
        Map> mapOfLists = new HashMap>();
        if (queryString == null || queryString.length() == 0) {
            return mapOfLists;
        }
        List list = URLEncodedUtils.parse(URI.create("http://localhost/?" + queryString), "UTF-8");
        for (NameValuePair pair : list) {
            List values = mapOfLists.get(pair.getName());
            if (values == null) {
                values = new ArrayList();
                mapOfLists.put(pair.getName(), values);
            }
            if (pair.getValue() != null) {
                values.add(pair.getValue());
            }
        }
    
        return mapOfLists;
    }
    

    A compatibility helper (values are stored in a String array just as in ServletRequest.getParameterMap()):

    public static Map getParameterMap(String queryString) {
        Map> mapOfLists = getParameterMapOfLists(queryString);
    
        Map mapOfArrays = new HashMap();
        for (String key : mapOfLists.keySet()) {
            mapOfArrays.put(key, mapOfLists.get(key).toArray(new String[] {}));
        }
    
        return mapOfArrays;
    }
    

提交回复
热议问题