Parsing query strings on Android

前端 未结 25 1094
时光说笑
时光说笑 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 18:08

    I don't think there is one in JRE. You can find similar functions in other packages like Apache HttpClient. If you don't use any other packages, you just have to write your own. It's not that hard. Here is what I use,

    public class QueryString {
    
     private Map> parameters;
    
     public QueryString(String qs) {
      parameters = new TreeMap>();
    
      // Parse query string
         String pairs[] = qs.split("&");
         for (String pair : pairs) {
                String name;
                String value;
                int pos = pair.indexOf('=');
                // for "n=", the value is "", for "n", the value is null
             if (pos == -1) {
              name = pair;
              value = null;
             } else {
           try {
            name = URLDecoder.decode(pair.substring(0, pos), "UTF-8");
                  value = URLDecoder.decode(pair.substring(pos+1, pair.length()), "UTF-8");            
           } catch (UnsupportedEncodingException e) {
            // Not really possible, throw unchecked
               throw new IllegalStateException("No UTF-8");
           }
             }
             List list = parameters.get(name);
             if (list == null) {
              list = new ArrayList();
              parameters.put(name, list);
             }
             list.add(value);
         }
     }
    
     public String getParameter(String name) {        
      List values = parameters.get(name);
      if (values == null)
       return null;
    
      if (values.size() == 0)
       return "";
    
      return values.get(0);
     }
    
     public String[] getParameterValues(String name) {        
      List values = parameters.get(name);
      if (values == null)
       return null;
    
      return (String[])values.toArray(new String[values.size()]);
     }
    
     public Enumeration getParameterNames() {  
      return Collections.enumeration(parameters.keySet()); 
     }
    
     public Map getParameterMap() {
      Map map = new TreeMap();
      for (Map.Entry> entry : parameters.entrySet()) {
       List list = entry.getValue();
       String[] values;
       if (list == null)
        values = null;
       else
        values = (String[]) list.toArray(new String[list.size()]);
       map.put(entry.getKey(), values);
      }
      return map;
     } 
    }
    

提交回复
热议问题