在Scala中,如何以编程方式构建带有查询字符串参数的URL?
另外,如何将包含查询字符串参数的URL的String
解析为允许我以编程方式编辑查询字符串参数的结构?
答案 0 :(得分:15)
喷雾非常efficient URI parser。用法如下:
import spray.http.Uri
val uri = Uri("http://example.com/test?param=param")
您可以像这样设置查询参数:
uri withQuery ("param2" -> "2", "param3" -> 3")
答案 1 :(得分:13)
以下库可以帮助您使用查询字符串参数解析和构建URL(免责声明:这是我自己的库):https://github.com/lemonlabsuk/scala-uri
它提供了一个用于使用查询字符串构建URL的DSL:
val uri = "http://example.com" ? ("one" -> 1) & ("two" -> 2)
您可以解析uri并将参数设置为Map[String,List[String]]
,如下所示:
val uri = parseUri("http://example.com?one=1&two=2").query.params
答案 2 :(得分:4)
Theon的图书馆看起来很不错。但是如果你只想要一个快速编码方法,我就有这个。它处理可选参数,并且还将识别来自spray-json的JsValues并在编码之前压缩它们。 (那些碰巧是我必须担心的两件事,但是你可以轻松地扩展匹配块以用于你想要特殊处理的其他情况)
import java.net.URLEncoder
def buildEncodedQueryString(params: Map[String, Any]): String = {
val encoded = for {
(name, value) <- params if value != None
encodedValue = value match {
case Some(x:JsValue) => URLEncoder.encode(x.compactPrint, "UTF8")
case x:JsValue => URLEncoder.encode(x.compactPrint, "UTF8")
case Some(x) => URLEncoder.encode(x.toString, "UTF8")
case x => URLEncoder.encode(x.toString, "UTF8")
}
} yield name + "=" + encodedValue
encoded.mkString("?", "&", "")
}
答案 3 :(得分:0)
尚未提及调度。
http://dispatch.databinder.net/Dispatch.html
val myRequest = "http://somehost.com" / "some" / "path" <<? Map("id" -> "12345")
答案 4 :(得分:0)
也很有用:https://github.com/mobiworx/urlifier
val url = (http || "some-domain".de) ? german & version(1) & foobar
url.toString
答案 5 :(得分:0)
sttp 为此提供了一个很好的URI内插器。
在此处查看Documentation
这里是例子:
import sttp.client._
import sttp.model._
val user = "Mary Smith"
val filter = "programming languages"
val endpoint: Uri = uri"http://example.com/$user/skills?filter=$filter"
assert(endpoint.toString ==
"http://example.com/Mary%20Smith/skills?filter=programming+languages")
如您所见,它会自动编码所需的部分。
答案 6 :(得分:0)
试试 KFoundation 的 URL 类。它既是构建器又是解析器。
例如
val url1 = URL("http://exampel.net/path")
val url2 = url1/"subpath" // -> http://exampel.net/path/subpath
val url3 = url2?("key"->"value") // -> http://exampel.net/path/subpath?key=value
API 文档:https://mscp.co/resouces/apidoc/kfoundation/scala/0.3/net/kfoundation/scala/io/URL.html 依赖:https://search.maven.org/artifact/net.kfoundation/kfoundation-scala_2.13/0.3.1/jar