1

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?
2
  • Are you sure that is a valid URL? stackoverflow.com/q/11490326/115145 stackoverflow.com/a/20422756/115145 Commented Jun 12, 2022 at 21:17
  • @CommonsWare As per the links that you provided, it seems like it is not. That query parameter should be encoded in the URL. If you can convert your comment to an answer, I'll mark it as an accepted answer and close this question. Thank you for finding and providing the supporting information. Commented Jun 12, 2022 at 22:22

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.