Parsing query strings on Android

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

提交回复
热议问题