Parse a URI String into Name-Value Collection

前端 未结 19 2452
难免孤独
难免孤独 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:01

    I had a go at a Kotlin version seeing how this is the top result in Google.

    @Throws(UnsupportedEncodingException::class)
    fun splitQuery(url: URL): Map> {
    
        val queryPairs = LinkedHashMap>()
    
        url.query.split("&".toRegex())
                .dropLastWhile { it.isEmpty() }
                .map { it.split('=') }
                .map { it.getOrEmpty(0).decodeToUTF8() to it.getOrEmpty(1).decodeToUTF8() }
                .forEach { (key, value) ->
    
                    if (!queryPairs.containsKey(key)) {
                        queryPairs[key] = arrayListOf(value)
                    } else {
    
                        if(!queryPairs[key]!!.contains(value)) {
                            queryPairs[key]!!.add(value)
                        }
                    }
                }
    
        return queryPairs
    }
    

    And the extension methods

    fun List.getOrEmpty(index: Int) : String {
        return getOrElse(index) {""}
    }
    
    fun String.decodeToUTF8(): String { 
        URLDecoder.decode(this, "UTF-8")
    }
    

提交回复
热议问题