Skip to content

Commit

Permalink
#48: %-encode plus in queries
Browse files Browse the repository at this point in the history
  • Loading branch information
adamw committed Nov 21, 2017
1 parent d47c312 commit 6b94630
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
12 changes: 9 additions & 3 deletions core/src/main/scala/com/softwaremill/sttp/Uri.scala
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,9 @@ case class Uri(scheme: String,
e match {
case QueryFragmentEncoding.All => URLEncoder.encode(s, "UTF-8")
case QueryFragmentEncoding.Standard =>
encode(Rfc3986.QueryNoStandardDelims, spaceAsPlus = true)(s)
encode(Rfc3986.QueryNoStandardDelims,
spaceAsPlus = true,
encodePlus = true)(s)
case QueryFragmentEncoding.Relaxed =>
encode(Rfc3986.Query, spaceAsPlus = true)(s)
}
Expand All @@ -161,13 +163,17 @@ case class Uri(scheme: String,
/**
* @param spaceAsPlus In the query, space is encoded as a `+`. In other
* contexts, it should be %-encoded as `%20`.
* @param encodePlus Should `+` (which is the encoded form of space
* in the query) be %-encoded.
*/
private def encode(allowedCharacters: Set[Char],
spaceAsPlus: Boolean = false)(s: String): String = {
spaceAsPlus: Boolean = false,
encodePlus: Boolean = false)(s: String): String = {
val sb = new StringBuilder()
// based on https://gist.github.com/teigen/5865923
for (c <- s) {
if (allowedCharacters(c)) sb.append(c)
if (c == '+' && encodePlus) sb.append("%2B") // #48
else if (allowedCharacters(c)) sb.append(c)
else if (c == ' ' && spaceAsPlus) sb.append('+')
else {
for (b <- c.toString.getBytes("UTF-8")) {
Expand Down
3 changes: 2 additions & 1 deletion core/src/test/scala/com/softwaremill/sttp/UriTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ class UriTests extends FunSuite with Matchers {
valueEncoding = QueryFragmentEncoding.Relaxed)) -> "k1%26=v1&",
List(QF.Plain("ą/ę&+;?", encoding = QueryFragmentEncoding.Relaxed)) -> "%C4%85/%C4%99&+;?",
List(QF.KeyValue("k", "v1,v2", valueEncoding = QueryFragmentEncoding.All)) -> "k=v1%2Cv2",
List(QF.KeyValue("k", "v1,v2")) -> "k=v1,v2"
List(QF.KeyValue("k", "v1,v2")) -> "k=v1,v2",
List(QF.KeyValue("k", "+1234")) -> "k=%2B1234"
)

for {
Expand Down

0 comments on commit 6b94630

Please sign in to comment.