How to decode URL-encoded and URL query strings in Scala

2 Answers

0 votes
import java.net.URLDecoder
import java.nio.charset.StandardCharsets

object UrlDecoderApp {

  /**
   * Decodes a URL-encoded string using UTF-8.
   *
   * @param encodedStr The URL-encoded string.
   * @return The decoded string, or the original string if decoding fails.
   */
  def decodeUrlString(encodedStr: String): String = {
    try {
      // URLDecoder handles %xx escapes and '+' to space conversion
      URLDecoder.decode(encodedStr, StandardCharsets.UTF_8.name())
    } catch {
      case e: Exception =>
        println(s"Decoding error: ${e.getMessage}")
        encodedStr
    }
  }

  def main(args: Array[String]): Unit = {
    // Example 1: Standard URL encoding with special characters
    val sample1 = "Hello%20World%21%20Scala%20%26%20Web"
    println("--- Example 1: Standard URL Encoding ---")
    println(s"Encoded: $sample1")
    println(s"Decoded: ${decodeUrlString(sample1)}")

    // Example 2: Form query string fragment encoding (spaces represented as '+')
    val sample2 = "Jane+Doe+from+New+York"
    println("\n--- Example 2: Form Fragment Encoding ---")
    println(s"Encoded: $sample2")
    println(s"Decoded: ${decodeUrlString(sample2)}")
  }
}


/*
run:

--- Example 1: Standard URL Encoding ---
Encoded: Hello%20World%21%20Scala%20%26%20Web
Decoded: Hello World! Scala & Web

--- Example 2: Form Fragment Encoding ---
Encoded: Jane+Doe+from+New+York
Decoded: Jane Doe from New York

*/

 



answered 5 hours ago by avibootz
0 votes
import java.net.URLDecoder
import java.nio.charset.StandardCharsets

object QueryStringParserApp {

  /**
   * Parses and decodes a full URL query string into a Map.
   *
   * @param queryString The query string (with or without leading '?').
   * @return A Map where each key maps to a list of decoded values.
   */
  def parseAndDecodeQuery(queryString: String): Map[String, List[String]] = {
    // Remove leading '?' if present
    val cleanQuery = if (queryString.startsWith("?")) queryString.drop(1) else queryString

    cleanQuery.split("&")
      .filter(_.nonEmpty)
      .map { param =>
        param.split("=", 2) match {
          case Array(k, v) =>
            val decodedKey = URLDecoder.decode(k, StandardCharsets.UTF_8.name())
            val decodedVal = URLDecoder.decode(v, StandardCharsets.UTF_8.name())
            (decodedKey, decodedVal)
          case Array(k) =>
            val decodedKey = URLDecoder.decode(k, StandardCharsets.UTF_8.name())
            (decodedKey, "")
        }
      }
      .groupBy(_._1)
      .view
      .mapValues(_.map(_._2).toList)
      .toMap
  }

  def main(args: Array[String]): Unit = {
    val fullQuery = "search=scala+tutorial&category=programming&tag=beginner&tag=functional"

    println("--- Full Query String Parsing ---")
    println(s"Original Query: $fullQuery")

    val result = parseAndDecodeQuery(fullQuery)

    println("Decoded Map Result:")
    result.foreach { case (key, values) =>
      println(s"  $key -> $values")
    }
  }
}


/*
run:

--- Full Query String Parsing ---
Original Query: search=scala+tutorial&category=programming&tag=beginner&tag=functional
Decoded Map Result:
  search -> List(scala tutorial)
  tag -> List(beginner, functional)
  category -> List(programming)

*/

 



answered 5 hours ago by avibootz
...