Parsing query strings on Android

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

    Origanally answered here

    On Android, there is Uri class in package android.net . Note that Uri is part of android.net, while URI is part of java.net .

    Uri class has many functions to extract query key-value pairs.

    Following function returns key-value pairs in the form of HashMap.

    In Java:

    Map<String, String> getQueryKeyValueMap(Uri uri){
        HashMap<String, String> keyValueMap = new HashMap();
        String key;
        String value;
    
        Set<String> keyNamesList = uri.getQueryParameterNames();
        Iterator iterator = keyNamesList.iterator();
    
        while (iterator.hasNext()){
            key = (String) iterator.next();
            value = uri.getQueryParameter(key);
            keyValueMap.put(key, value);
        }
        return keyValueMap;
    }
    

    In Kotlin:

    fun getQueryKeyValueMap(uri: Uri): HashMap<String, String> {
            val keyValueMap = HashMap<String, String>()
            var key: String
            var value: String
    
            val keyNamesList = uri.queryParameterNames
            val iterator = keyNamesList.iterator()
    
            while (iterator.hasNext()) {
                key = iterator.next() as String
                value = uri.getQueryParameter(key) as String
                keyValueMap.put(key, value)
            }
            return keyValueMap
        }
    
    0 讨论(0)
  • 2020-11-22 17:59

    Answering here because this is a popular thread. This is a clean solution in Kotlin that uses the recommended UrlQuerySanitizer api. See the official documentation. I have added a string builder to concatenate and display the params.

        var myURL: String? = null
        // if the url is sent from a different activity where you set it to a value
        if (intent.hasExtra("my_value")) {
            myURL = intent.extras.getString("my_value")
        } else {
            myURL = intent.dataString
        }
    
        val sanitizer = UrlQuerySanitizer(myURL)
        // We don't want to manually define every expected query *key*, so we set this to true
        sanitizer.allowUnregisteredParamaters = true
        val parameterNamesToValues: List<UrlQuerySanitizer.ParameterValuePair> = sanitizer.parameterList
        val parameterIterator: Iterator<UrlQuerySanitizer.ParameterValuePair> = parameterNamesToValues.iterator()
    
        // Helper simply so we can display all values on screen
        val stringBuilder = StringBuilder()
    
        while (parameterIterator.hasNext()) {
            val parameterValuePair: UrlQuerySanitizer.ParameterValuePair = parameterIterator.next()
            val parameterName: String = parameterValuePair.mParameter
            val parameterValue: String = parameterValuePair.mValue
    
            // Append string to display all key value pairs
            stringBuilder.append("Key: $parameterName\nValue: $parameterValue\n\n")
        }
    
        // Set a textView's text to display the string
        val paramListString = stringBuilder.toString()
        val textView: TextView = findViewById(R.id.activity_title) as TextView
        textView.text = "Paramlist is \n\n$paramListString"
    
        // to check if the url has specific keys
        if (sanitizer.hasParameter("type")) {
            val type = sanitizer.getValue("type")
            println("sanitizer has type param $type")
        }
    
    0 讨论(0)
  • 2020-11-22 18:00

    On Android, the Apache libraries provide a Query parser:

    http://developer.android.com/reference/org/apache/http/client/utils/URLEncodedUtils.html and http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html

    0 讨论(0)
  • 2020-11-22 18:02

    On Android its simple as the code below:

    UrlQuerySanitizer sanitzer = new UrlQuerySanitizer(url);
    String value = sanitzer.getValue("your_get_parameter");
    

    Also if you don't want to register each expected query key use:

    sanitzer.setAllowUnregisteredParamaters(true)
    

    Before calling:

    sanitzer.parseUrl(yourUrl)
    
    0 讨论(0)
  • 2020-11-22 18:06

    This works for me.. I'm not sure why every one was after a Map, List> All I needed was a simple name value Map.

    To keep things simple I used the build in URI.getQuery();

    public static Map<String, String> getUrlParameters(URI uri)
        throws UnsupportedEncodingException {
        Map<String, String> params = new HashMap<String, String>();
        for (String param : uri.getQuery().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");
            }
            params.put(new String(key), new String(value));
        }
        return params;
    }
    
    0 讨论(0)
  • 2020-11-22 18:06

    Use Apache HttpComponents and wire it up with some collection code to access params by value: http://www.joelgerard.com/2012/09/14/parsing-query-strings-in-java-and-accessing-values-by-key/

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