Parsing query strings on Android

前端 未结 25 1080
时光说笑
时光说笑 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:48

    You say "Java" but "not Java EE". Do you mean you are using JSP and/or servlets but not a full Java EE stack? If that's the case, then you should still have request.getParameter() available to you.

    If you mean you are writing Java but you are not writing JSPs nor servlets, or that you're just using Java as your reference point but you're on some other platform that doesn't have built-in parameter parsing ... Wow, that just sounds like an unlikely question, but if so, the principle would be:

    xparm=0
    word=""
    loop
      get next char
      if no char
        exit loop
      if char=='='
        param_name[xparm]=word
        word=""
      else if char=='&'
        param_value[xparm]=word
        word=""
        xparm=xparm+1
      else if char=='%'
        read next two chars
        word=word+interpret the chars as hex digits to make a byte
      else
        word=word+char
    

    (I could write Java code but that would be pointless, because if you have Java available, you can just use request.getParameters.)

    0 讨论(0)
  • 2020-11-22 17:49

    Here is BalusC's answer, but it compiles and returns results:

    public static Map<String, List<String>> getUrlParameters(String url)
            throws UnsupportedEncodingException {
        Map<String, List<String>> params = new HashMap<String, List<String>>();
        String[] urlParts = url.split("\\?");
        if (urlParts.length > 1) {
            String query = urlParts[1];
            for (String param : query.split("&")) {
                String pair[] = param.split("=");
                String key = URLDecoder.decode(pair[0], "UTF-8");
                String value = "";
                if (pair.length > 1) {
                    value = URLDecoder.decode(pair[1], "UTF-8");
                }
                List<String> values = params.get(key);
                if (values == null) {
                    values = new ArrayList<String>();
                    params.put(key, values);
                }
                values.add(value);
            }
        }
        return params;
    }
    
    0 讨论(0)
  • 2020-11-22 17:49

    If you're using Spring 3.1 or greater (yikes, was hoping that support went back further), you can use the UriComponents and UriComponentsBuilder:

    UriComponents components = UriComponentsBuilder.fromUri(uri).build();
    List<String> myParam = components.getQueryParams().get("myParam");
    

    components.getQueryParams() returns a MultiValueMap<String, String>

    Here's some more documentation.

    0 讨论(0)
  • 2020-11-22 17:51

    On Android:

    import android.net.Uri;
    
    [...]
    
    Uri uri=Uri.parse(url_string);
    uri.getQueryParameter("para1");
    
    0 讨论(0)
  • 2020-11-22 17:53

    Since Android M things have got more complicated. The answer of android.net.URI.getQueryParameter() has a bug which breaks spaces before JellyBean. Apache URLEncodedUtils.parse() worked, but was deprecated in L, and removed in M.

    So the best answer now is UrlQuerySanitizer. This has existed since API level 1 and still exists. It also makes you think about the tricky issues like how do you handle special characters, or repeated values.

    The simplest code is

    UrlQuerySanitizer.ValueSanitizer sanitizer = UrlQuerySanitizer.getAllButNullLegal();
    // remember to decide if you want the first or last parameter with the same name
    // If you want the first call setPreferFirstRepeatedParameter(true);
    sanitizer.parseUrl(url);
    String value = sanitizer.getValue("paramName"); // get your value
    

    If you are happy with the default parsing behavior you can do:

    new UrlQuerySanitizer(url).getValue("paramName")
    

    but you should make sure you understand what the default parsing behavor is, as it might not be what you want.

    0 讨论(0)
  • 2020-11-22 17:53

    I have methods to achieve this:

    1):

    public static String getQueryString(String url, String tag) {
        String[] params = url.split("&");
        Map<String, String> map = new HashMap<String, String>();
        for (String param : params) {
            String name = param.split("=")[0];
            String value = param.split("=")[1];
            map.put(name, value);
        }
    
        Set<String> keys = map.keySet();
        for (String key : keys) {
            if(key.equals(tag)){
             return map.get(key);
            }
            System.out.println("Name=" + key);
            System.out.println("Value=" + map.get(key));
        }
        return "";
    }
    

    2) and the easiest way to do this Using Uri class:

    public static String getQueryString(String url, String tag) {
        try {
            Uri uri=Uri.parse(url);
            return uri.getQueryParameter(tag);
        }catch(Exception e){
            Log.e(TAG,"getQueryString() " + e.getMessage());
        }
        return "";
    }
    

    and this is an example of how to use either of two methods:

    String url = "http://www.jorgesys.com/advertisements/publicidadmobile.htm?position=x46&site=reform&awidth=800&aheight=120";      
    String tagValue = getQueryString(url,"awidth");
    

    the value of tagValue is 800

    0 讨论(0)
提交回复
热议问题