the right way to POST application/x-www-form-urlencoded

2,411 views
Skip to first unread message

David Riccitelli

unread,
Oct 21, 2013, 6:06:01 AM10/21/13
to spray...@googlegroups.com
Hello,

Is this the right way to POST x-www-form-urlencoded data using spray client (it works), or is it there a DSL to set POST params?

    val raw = "param1=%1$s&param2=%2$s&param3=%3$s".format(
      URLEncoder.encode(value1, "UTF-8"),
      URLEncoder.encode(value2, "UTF-8"),
      URLEncoder.encode(value3, "UTF-8")
    )
    
    val request = HttpRequest(method = POST, uri = "https://example.org/path",
      entity = HttpEntity(MediaTypes.`application/x-www-form-urlencoded`, raw))

    val pipeline: HttpRequest => Future[MyClass] = (
        encode(Gzip)
        ~> sendReceive
        ~> decode(Deflate)
        ~> unmarshal[MyClass]
      )

    pipeline(request) onComplete {
      case Success(myClass) => // ... add shutdown()
      case Failure(error) => // ... add shutdown()
    }

Mathias Doenitz

unread,
Oct 21, 2013, 6:13:09 AM10/21/13
to spray...@googlegroups.com
David,

you can use the `FormData` class (https://github.com/spray/spray/blob/master/spray-http/src/main/scala/spray/http/HttpForm.scala#L29), which has a predefined marshaller.
So, rather than saying:

> val raw = "param1=%1$s&param2=%2$s&param3=%3$s".format(
> URLEncoder.encode(value1, "UTF-8"),
> URLEncoder.encode(value2, "UTF-8"),
> URLEncoder.encode(value3, "UTF-8")
> )
>
> val request = HttpRequest(method = POST, uri =
> "https://example.org/path",
> entity = HttpEntity(MediaTypes.`application/x-www-form-urlencoded`,
> raw))

you can just say:

val data = Map("param1" -> value1, "param2" -> value2, "param3" -> value3)
val request = Post("https://example.org/path", FormData(data))

Cheers,
Mathias

---
mat...@spray.io
http://spray.io
> --
> You received this message because you are subscribed to the Google Groups "spray-user" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to spray-user+...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.

---
mat...@spray.io
http://spray.io

David Riccitelli

unread,
Oct 21, 2013, 7:07:30 AM10/21/13
to spray...@googlegroups.com
It works great, spray is great, thanks Mathias!



══════════════════════════════════════════════
► Twitter: @ziodave                                      
---                                              
 InsideOut10 s.r.l. (IT-11381771002)
══════════════════════════════════════════════



--
You received this message because you are subscribed to a topic in the Google Groups "spray-user" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/spray-user/JjA2LCLfib8/unsubscribe.
To unsubscribe from this group and all its topics, send an email to spray-user+...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages