Parsing query strings on Android Parsing query strings on Android java java

Parsing query strings on Android


On Android:

import android.net.Uri;[...]Uri uri=Uri.parse(url_string);uri.getQueryParameter("para1");


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");

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.