Parse a URI String into Name-Value Collection

前端 未结 19 2498
难免孤独
难免孤独 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 02:00

    Kotlin's Answer with initial reference from https://stackoverflow.com/a/51024552/3286489, but with improved version by tidying up codes and provides 2 versions of it, and use immutable collection operations

    Use java.net.URI to extract the Query. Then use the below provided extension functions

    1. Assuming you only want the last value of query i.e. page2&page3 will get {page=3}, use the below extension function
        fun URI.getQueryMap(): Map {
            if (query == null) return emptyMap()
    
            return query.split("&")
                    .mapNotNull { element -> element.split("=")
                            .takeIf { it.size == 2 && it.none { it.isBlank() } } }
                    .associateBy({ it[0].decodeUTF8() }, { it[1].decodeUTF8() })
        }
    
        private fun String.decodeUTF8() = URLDecoder.decode(this, "UTF-8") // decode page=%22ABC%22 to page="ABC"
    
    1. Assuming you want a list of all value for the query i.e. page2&page3 will get {page=[2, 3]}
        fun URI.getQueryMapList(): Map> {
            if (query == null) return emptyMap()
    
            return query.split("&")
                    .distinct()
                    .mapNotNull { element -> element.split("=")
                            .takeIf { it.size == 2 && it.none { it.isBlank() } } }
                    .groupBy({ it[0].decodeUTF8() }, { it[1].decodeUTF8() })
        }
    
        private fun String.decodeUTF8() = URLDecoder.decode(this, "UTF-8") // decode page=%22ABC%22 to page="ABC"
    

    The way to use it as below

        val uri = URI("schema://host/path/?page=&page=2&page=2&page=3")
        println(uri.getQueryMapList()) // Result is {page=[2, 3]}
        println(uri.getQueryMap()) // Result is {page=3}
    

提交回复
热议问题