Created
August 28, 2012 22:08
-
-
Save jaytaylor/3504765 to your computer and use it in GitHub Desktop.
Scala query string parser using Java Collections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.URLDecoder | |
import java.util.{ArrayList, HashMap, List, Map} | |
import scala.collection.JavaConversions._ | |
/** | |
* Parse the query string portion of a string containing a URI or URL. | |
*/ | |
/** | |
* Parse the query string portion of a string containing a URI or URL. | |
*/ | |
def parseUriParameters(uri: String): Map[String, List[String]] = { | |
val params = new HashMap[String, List[String]]() | |
val parts = uri split "\\?" | |
if (parts.length > 1) { | |
val query = parts(1) | |
query split "&" map { param => | |
val pair = param split "=" | |
val key = URLDecoder.decode(pair(0), "UTF-8") | |
val value = pair.length match { | |
case l if l > 1 => URLDecoder.decode(pair(1), "UTF-8") | |
case _ => "" | |
} | |
val values = Option(params get key) match { | |
case Some(values) => values | |
case None => | |
val v = new ArrayList[String]() | |
params.put(key, v) | |
v | |
} | |
values add value // NB: The value may be an empty string. | |
} | |
} | |
params | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Refactored this to be pure Scala