Scala - URL with Query String Parser and Builder DSL

六眼飞鱼酱① 提交于 2019-11-29 11:21:39

问题


In Scala how do I build up a URL with query string parameters programmatically?

Also how can I parse a String containing a URL with query string parameters into a structure that allows me to edit the query string parameters programmatically?


回答1:


Spray has a very efficient URI parser. Usage is like so:

import spray.http.Uri
val uri = Uri("http://example.com/test?param=param")

You can set the query params like so:

uri withQuery ("param2" -> "2", "param3" -> 3")



回答2:


The following library can help you parse and build URLs with query string parameters (Disclaimer: This is my own library): https://github.com/lemonlabsuk/scala-uri

It provides a DSL for building URLs with query strings:

val uri = "http://example.com" ? ("one" -> 1) & ("two" -> 2)

You can parse a uri and get the parameters into a Map[String,List[String]] like so:

val uri = parseUri("http://example.com?one=1&two=2").query.params



回答3:


Theon's library looks pretty nice. But if you just want a quickie encode method, I have this one. It deals with optional parameters, and also will recognize JsValues from spray-json and compact print them before encoding. (Those happen to be the two things I have to worry about, but you could easily extend the match block for other cases you want to give special handling to)

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("?", "&", "")
}



回答4:


Dispatch hasn't been mentioned yet.

http://dispatch.databinder.net/Dispatch.html

val myRequest = "http://somehost.com" / "some" / "path" <<? Map("id" -> "12345")



回答5:


also useful: https://github.com/mobiworx/urlifier

val url = (http || "some-domain".de) ? german & version(1) & foobar
url.toString


来源:https://stackoverflow.com/questions/13463387/scala-url-with-query-string-parser-and-builder-dsl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!