Parsing query strings on Android

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

    On Android, you can use the Uri.parse static method of the android.net.Uri class to do the heavy lifting. If you're doing anything with URIs and Intents you'll want to use it anyways.

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

    using Guava:

    Multimap<String,String> parseQueryString(String queryString, String encoding) {
        LinkedListMultimap<String, String> result = LinkedListMultimap.create();
    
        for(String entry : Splitter.on("&").omitEmptyStrings().split(queryString)) {
            String pair [] = entry.split("=", 2);
            try {
                result.put(URLDecoder.decode(pair[0], encoding), pair.length == 2 ? URLDecoder.decode(pair[1], encoding) : null);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
    
        return result;
    }
    
    0 讨论(0)
  • 2020-11-22 17:54

    On Android, I tried using @diyism answer but I encountered the space character issue raised by @rpetrich, for example: I fill out a form where username = "us+us" and password = "pw pw" causing a URL string to look like:

    http://somewhere?username=us%2Bus&password=pw+pw
    

    However, @diyism code returns "us+us" and "pw+pw", i.e. it doesn't detect the space character. If the URL was rewritten with %20 the space character gets identified:

    http://somewhere?username=us%2Bus&password=pw%20pw
    

    This leads to the following fix:

    Uri uri = Uri.parse(url_string.replace("+", "%20"));
    uri.getQueryParameter("para1");
    
    0 讨论(0)
  • 2020-11-22 17:55

    For a servlet or a JSP page you can get querystring key/value pairs by using request.getParameter("paramname")

    String name = request.getParameter("name");
    

    There are other ways of doing it but that's the way I do it in all the servlets and jsp pages that I create.

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

    Parsing the query string is a bit more complicated than it seems, depending on how forgiving you want to be.

    First, the query string is ascii bytes. You read in these bytes one at a time and convert them to characters. If the character is ? or & then it signals the start of a parameter name. If the character is = then it signals the start of a paramter value. If the character is % then it signals the start of an encoded byte. Here is where it gets tricky.

    When you read in a % char you have to read the next two bytes and interpret them as hex digits. That means the next two bytes will be 0-9, a-f or A-F. Glue these two hex digits together to get your byte value. But remember, bytes are not characters. You have to know what encoding was used to encode the characters. The character é does not encode the same in UTF-8 as it does in ISO-8859-1. In general it's impossible to know what encoding was used for a given character set. I always use UTF-8 because my web site is configured to always serve everything using UTF-8 but in practice you can't be certain. Some user-agents will tell you the character encoding in the request; you can try to read that if you have a full HTTP request. If you just have a url in isolation, good luck.

    Anyway, assuming you are using UTF-8 or some other multi-byte character encoding, now that you've decoded one encoded byte you have to set it aside until you capture the next byte. You need all the encoded bytes that are together because you can't url-decode properly one byte at a time. Set aside all the bytes that are together then decode them all at once to reconstruct your character.

    Plus it gets more fun if you want to be lenient and account for user-agents that mangle urls. For example, some webmail clients double-encode things. Or double up the ?&= chars (for example: http://yoursite.com/blah??p1==v1&&p2==v2). If you want to try to gracefully deal with this, you will need to add more logic to your parser.

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

    Based on the answer from BalusC, i wrote some example-Java-Code:

        if (queryString != null)
        {
            final String[] arrParameters = queryString.split("&");
            for (final String tempParameterString : arrParameters)
            {
                final String[] arrTempParameter = tempParameterString.split("=");
                if (arrTempParameter.length >= 2)
                {
                    final String parameterKey = arrTempParameter[0];
                    final String parameterValue = arrTempParameter[1];
                    //do something with the parameters
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题