Home > front end >  Not able to get query paramter value using android.net.Uri#getQueryParameter
Not able to get query paramter value using android.net.Uri#getQueryParameter

Time:06-13

I'm trying to parse query parameters from a URL string using Uri.getQueryParameter(String key) but that method returns null for the passed-in key. That URL that I'm using is /endpoint/path?query1=foo&page[size]=1. I'm able to successfully get the value for query1 parameter but not for page[size](the method returns null for this key). My code looks like:

import android.net.Uri

val uri = Uri.parse("/endpoint/path?query1=foo&page[size]=1")
val queryParameterNames = uri.getQueryParameterNames()

println(queryParameterNames) // prints ["query1", "page[size]"]

val map = mutableMapOf<String, String>()
queryParameterNames.forEach { name ->
    map[name] = uri.getQueryParameter(name) ?: ""
}

println(map) // prints {query1=foo, page[size]=}

As seen in the output of the last line, the value of page[size] is empty. I suspect it has something to do with [, ] characters in the query parameter name for page[size], with them being url encoded while looking for the value but I'm not sure why this is actually failing. So, I have a couple of questions here:

  1. Why is it successful in finding the names for the query parameters but fails when finding their corresponding values?
  2. How can I get the value of page[size] parameter from the url string in Android?

CodePudding user response:

I think that Android's Uri implementation is getting confused over those square brackets, as those appear to be invalid URL syntax.

If you control the Web service, you might reconsider the use of square brackets, as they may cause problems with other clients. Otherwise, you may need to play some icky regex games to replace those square brackets with escaped equivalents or otherwise find ways to sanitize the URL before fully parsing it with Uri.

  • Related