正确编码spray.http.Uri.Path?

时间:2016-05-01 22:25:19

标签: scala spray

我想正确地对网址进行编码:http://a.b.c/apis/POST /foo/bar其中POST /foo/bar应编码为:POST%20%2Ffoo%2Fbar

这是我试过的:

scala> import spray.http._
import spray.http._

scala> val base = Uri("http:/a.b.c")
base: spray.http.Uri = http:///a.b.c

scala> val path = Uri.Path("/apis/GET /foo/bar")
path: spray.http.Uri.Path = /apis/GET%20/foo/bar

scala> base.withPath(path)
res0: spray.http.Uri = http:///apis/GET%20/foo/bar

但是,上面显示的是/foo/bar作为附加路径字段,而不是GET%20%2Ffoo%2Fbar

另外,我试过了:

scala> Uri.Path("/apis/" + java.net.URLEncoder.encode("GET /foo/bar", "UTF-8"))
res1: spray.http.Uri.Path = /apis/GET+%2Ffoo%2Fbar

但是,根据https://stackoverflow.com/a/2678602/409976,空格应在路径部分编码为%20(据我所知)。此外,使用+而不是%20时,我正在访问的Web服务会返回HTTP-500。

1 个答案:

答案 0 :(得分:2)

scala> Uri("http:/a.b.c").path / "apis" / "GET /foo/bar"
res0: spray.http.Uri.Path = /a.b.c/apis/GET%20%2Ffoo%2Fbar