Skip to content

Instantly share code, notes, and snippets.

@mr5z
Last active October 14, 2022 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mr5z/de15062108a8c4e0375a88f401e098f0 to your computer and use it in GitHub Desktop.
Save mr5z/de15062108a8c4e0375a88f401e098f0 to your computer and use it in GitHub Desktop.
Trying to replicate C#'s Uri.EscapeUriString()
fun tryEncode(url: String): URL {
val schemeSeparator = "://"
val schemeIndex = url.indexOf(schemeSeparator)
val scheme: String
val urlWithoutScheme: String
if (schemeIndex > 0) {
scheme = url.substring(0, schemeIndex)
urlWithoutScheme = url.substring(schemeIndex + schemeSeparator.length)
}
else {
scheme = "https"
urlWithoutScheme = url
}
val pathWithQueryString = urlWithoutScheme.replace(authority, "")
val components = pathWithQueryString.split('?')
val queryWithFragment = if (components.size > 1) components.last() else ""
val subcomponent = queryWithFragment.split('#')
val authority = urlWithoutScheme.substring(0, urlWithoutScheme.indexOf('/'))
val path = components.firstOrNull()
val query = subcomponent.firstOrNull()
val fragment = if (subcomponent.size > 1) subcomponent.last() else ""
return URI(scheme, authority, path, query, fragment).toURL()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment