Parse a URI String into Name-Value Collection

前端 未结 19 2524
难免孤独
难免孤独 2020-11-22 01:34

I\'ve got the URI like this:

https://google.com.ua/oauth/authorize?client_id=SS&response_type=code&scope=N_FULL&access_type=offline&redirect_         


        
19条回答
  •  臣服心动
    2020-11-22 01:47

    On Android, there is a 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 key-value pairs from a query.

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

    In Java:

    Map getQueryKeyValueMap(Uri uri){
        HashMap keyValueMap = new HashMap();
        String key;
        String value;
    
        Set 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 {
            val keyValueMap = HashMap()
            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
        }
    

提交回复
热议问题