or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication.mdcontent-processing.mdcontent-types.mdcookies.mddate-utilities.mdheader-parsing.mdheaders.mdhttp-message-extensions.mdhttp-methods-status.mdindex.mdmultipart.mdparameters.mdurl-encoding.mdurl-handling.md
tile.json

url-encoding.mddocs/

URL Encoding and Decoding

Comprehensive URL encoding and decoding functions for all URL components, supporting percent encoding, query parameter encoding, OAuth encoding, and path segment encoding with proper charset handling.

Capabilities

Query Component Encoding

Encodes strings for use in URL query parameters with control over space handling and encoding depth.

/**
 * Encode string as URL query component
 * @param encodeFull if true, encode all reserved characters; if false, preserve URL protocol characters
 * @param spaceToPlus if true, encode spaces as '+'; if false, encode as '%20'
 * @param charset character encoding to use (defaults to UTF-8)
 * @return percent-encoded string suitable for URL query components
 */
fun String.encodeURLQueryComponent(
    encodeFull: Boolean = false,
    spaceToPlus: Boolean = false,
    charset: Charset = Charsets.UTF_8
): String

Usage Examples:

import io.ktor.http.*

// Basic query component encoding
val encoded = "hello world".encodeURLQueryComponent()
println(encoded) // "hello%20world"

// Encode spaces as plus signs
val withPlus = "hello world".encodeURLQueryComponent(spaceToPlus = true)
println(withPlus) // "hello+world"

// Full encoding mode
val fullEncoded = "path?param=value".encodeURLQueryComponent(encodeFull = true)
println(fullEncoded) // "path%3Fparam%3Dvalue"

// Custom charset
val customCharset = "café".encodeURLQueryComponent(charset = Charsets.ISO_8859_1)

Path Encoding

Encodes URL paths and path segments with proper handling of forward slashes.

/**
 * Encode complete URL path, preserving forward slashes
 * @return percent-encoded path with slashes preserved
 */
fun String.encodeURLPath(): String

/**
 * Encode URL path segment, encoding all characters including slashes
 * @return percent-encoded path segment
 */
fun String.encodeURLPathPart(): String

Usage Examples:

import io.ktor.http.*

// Encode complete path (preserves slashes)
val path = "/api/users/john doe".encodeURLPath()
println(path) // "/api/users/john%20doe"

// Encode path segment (encodes slashes too)
val segment = "users/john".encodeURLPathPart()
println(segment) // "users%2Fjohn"

// Handle special characters
val complexPath = "/files/résumé (final).pdf".encodeURLPath()
println(complexPath) // "/files/r%C3%A9sum%C3%A9%20%28final%29.pdf"

Parameter Encoding

Encodes strings for use as URL parameter keys and values.

/**
 * Encode string as URL parameter key or value
 * @param spaceToPlus if true, encode spaces as '+'; if false, encode as '%20'
 * @return percent-encoded parameter string
 */
fun String.encodeURLParameter(spaceToPlus: Boolean = false): String

Usage Examples:

import io.ktor.http.*

// Encode parameter key
val paramKey = "filter by name".encodeURLParameter()
println(paramKey) // "filter%20by%20name"

// Encode parameter value with plus encoding
val paramValue = "john doe".encodeURLParameter(spaceToPlus = true)
println(paramValue) // "john+doe"

// Special characters in parameters
val specialParam = "user@domain.com".encodeURLParameter()
println(specialParam) // "user%40domain.com"

OAuth Encoding

Special encoding for OAuth 1.0 parameter values according to RFC 5849.

/**
 * Encode string for OAuth 1.0 parameter values
 * @return percent-encoded string suitable for OAuth signatures
 */
fun String.encodeOAuth(): String

Usage Examples:

import io.ktor.http.*

// OAuth parameter encoding
val oauthParam = "callback_url=http://example.com".encodeOAuth()
println(oauthParam) // "callback_url%3Dhttp%3A//example.com"

// OAuth signature base string components
val method = "POST".encodeOAuth()
val url = "https://api.example.com/1/statuses/update.json".encodeOAuth()
val params = "oauth_consumer_key=key&status=Hello World!".encodeOAuth()

Query Component Decoding

Decodes percent-encoded URL query components with charset and space handling options.

/**
 * Decode percent-encoded URL query component
 * @param start start index in string (defaults to 0)
 * @param end end index in string (defaults to string length)
 * @param plusIsSpace if true, decode '+' as space; if false, treat '+' literally
 * @param charset character encoding to use (defaults to UTF-8)
 * @return decoded string
 */
fun String.decodeURLQueryComponent(
    start: Int = 0,
    end: Int = length,
    plusIsSpace: Boolean = false,
    charset: Charset = Charsets.UTF_8
): String

Usage Examples:

import io.ktor.http.*

// Basic query decoding
val decoded = "hello%20world".decodeURLQueryComponent()
println(decoded) // "hello world"

// Decode with plus as space
val withPlus = "hello+world".decodeURLQueryComponent(plusIsSpace = true)
println(withPlus) // "hello world"

// Decode substring
val partial = "prefix%20hello%20world%20suffix".decodeURLQueryComponent(
    start = 7, 
    end = 19
)
println(partial) // "hello world"

// Custom charset decoding
val customDecoded = "caf%E9".decodeURLQueryComponent(charset = Charsets.ISO_8859_1)
println(customDecoded) // "café"

URL Part Decoding

Decodes percent-encoded URL parts without treating plus signs as spaces.

/**
 * Decode percent-encoded URL part
 * @param start start index in string (defaults to 0)
 * @param end end index in string (defaults to string length)
 * @param charset character encoding to use (defaults to UTF-8)
 * @return decoded string
 */
fun String.decodeURLPart(
    start: Int = 0,
    end: Int = length,
    charset: Charset = Charsets.UTF_8
): String

Usage Examples:

import io.ktor.http.*

// Decode URL path part
val pathPart = "/api/users%2Fjohn%20doe".decodeURLPart()
println(pathPart) // "/api/users/john doe"

// Decode with plus signs preserved
val withPlus = "math%2B%2B".decodeURLPart()
println(withPlus) // "math++"

// Decode complex Unicode
val unicode = "r%C3%A9sum%C3%A9".decodeURLPart()
println(unicode) // "résumé"

// Decode substring
val partial = "prefix%20decoded%20suffix".decodeURLPart(start = 7, end = 15)
println(partial) // "decoded"

URL Decode Exception

Exception thrown when URL decoding fails due to malformed percent sequences.

/**
 * Exception thrown for malformed percent-encoded sequences
 * @param message error description
 */
class URLDecodeException(message: String) : Exception

Usage Examples:

import io.ktor.http.*

// Handle decoding errors
try {
    val malformed = "incomplete%2".decodeURLPart()
} catch (e: URLDecodeException) {
    println("Decoding failed: ${e.message}")
    // "Decoding failed: Incomplete trailing HEX escape: %2, in incomplete%2 at 10"
}

try {
    val badHex = "invalid%GG".decodeURLPart()
} catch (e: URLDecodeException) {
    println("Invalid hex: ${e.message}")
    // "Invalid hex: Wrong HEX escape: %GG, in invalid%GG, at 7"
}

// Safe decoding with error handling
fun safeDecodeURL(encoded: String): String? {
    return try {
        encoded.decodeURLPart()
    } catch (e: URLDecodeException) {
        null // Return null for malformed URLs
    }
}

Complete URL Encoding Examples

import io.ktor.http.*

// Build complete encoded URL
fun buildEncodedURL(
    baseUrl: String,
    pathSegments: List<String>,
    queryParams: Map<String, String>
): String {
    val encodedPath = pathSegments.joinToString("/") { it.encodeURLPathPart() }
    val encodedQuery = queryParams.entries.joinToString("&") { (key, value) ->
        "${key.encodeURLParameter()}=${value.encodeURLParameter(spaceToPlus = true)}"
    }
    
    return "$baseUrl/$encodedPath?$encodedQuery"
}

// Usage
val url = buildEncodedURL(
    baseUrl = "https://api.example.com",
    pathSegments = listOf("users", "john doe", "profile"),
    queryParams = mapOf(
        "include fields" to "name,email",
        "format" to "json"
    )
)
println(url)
// "https://api.example.com/users/john%20doe/profile?include+fields=name%2Cemail&format=json"

// Parse and decode URL components
fun parseEncodedURL(url: String): Map<String, Any> {
    val parts = url.split('?', limit = 2)
    val pathAndQuery = parts.getOrNull(1) ?: ""
    
    val pathParts = parts[0].split('/').drop(3) // Skip protocol and host
        .map { it.decodeURLPart() }
    
    val queryParams = if (pathAndQuery.isNotEmpty()) {
        pathAndQuery.split('&').associate { param ->
            val (key, value) = param.split('=', limit = 2)
            key.decodeURLQueryComponent(plusIsSpace = true) to 
            value.decodeURLQueryComponent(plusIsSpace = true)
        }
    } else emptyMap()
    
    return mapOf(
        "pathSegments" to pathParts,
        "queryParams" to queryParams
    )
}

// OAuth 1.0 signature base string creation
fun createOAuthSignatureBase(
    httpMethod: String,
    baseUrl: String,
    parameters: Map<String, String>
): String {
    val encodedMethod = httpMethod.encodeOAuth()
    val encodedUrl = baseUrl.encodeOAuth()
    
    val encodedParams = parameters.toSortedMap()
        .map { (key, value) -> "${key.encodeOAuth()}=${value.encodeOAuth()}" }
        .joinToString("&")
        .encodeOAuth()
    
    return "$encodedMethod&$encodedUrl&$encodedParams"
}

Types

// Uses standard Charset from Kotlin stdlib
// No additional types specific to URL encoding