Parse a URI String into Name-Value Collection

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

    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 (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)
提交回复
热议问题