Skip to content

Commit

Permalink
URIBuilder handles special characters
Browse files Browse the repository at this point in the history
  • Loading branch information
Akirathan committed Feb 16, 2024
1 parent 0e2b1d6 commit c5cc2dc
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.enso.downloader.http

import java.net.URI
import java.net.{URI, URLEncoder}
import java.nio.charset.StandardCharsets

/** A simple immutable builder for URIs based on URLs.
*
Expand All @@ -25,13 +26,15 @@ case class URIBuilder private (uri: URI) {
* The query is appended at the end.
*/
def addQuery(key: String, value: String): URIBuilder = {
val scheme = uri.getScheme
val authority = uri.getAuthority
val path = uri.getPath
val query = if (uri.getQuery == null) "" else uri.getQuery + "&"
val fragment = uri.getFragment
val newQuery = query + key + "=" + value
val newUri = new URI(scheme, authority, path, newQuery, fragment)
val scheme = uri.getScheme
val authority = uri.getAuthority
val path = uri.getPath
val query = if (uri.getQuery == null) "" else uri.getQuery + "&"
val fragment = uri.getFragment
val encodedKey = URLEncoder.encode(key, StandardCharsets.UTF_8)
val encodedValue = URLEncoder.encode(value, StandardCharsets.UTF_8)
val newQuery = query + encodedKey + "=" + encodedValue
val newUri = new URI(scheme, authority, path, newQuery, fragment)
copy(newUri)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ class URIBuilderSpec extends AnyWordSpec with Matchers {
val uri = bldr.addQuery("foo", "bar").addQuery("baz", "qux").build()
uri.toString mustEqual "http://google.com?foo=bar&baz=qux"
}

"Handle non-standard symbols in queries" in {
val bldr = URIBuilder.fromUri("http://google.com")
val uri = bldr.addQuery("foo", "bar baz").addQuery("baz", "qux").build()
uri.toString mustEqual "http://google.com?foo=bar+baz&baz=qux"
}
}

}

0 comments on commit c5cc2dc

Please sign in to comment.