How to get the body of post request in Scalatra?
Asked Answered
A

2

14

I have a scalatra servlet:

post("/asdf") {
  ???
}

And my clients send xml in post body, so I need to extract raw text from request. How do I do it in scalatra?

Aideaidedecamp answered 28/3, 2012 at 16:26 Comment(0)
Q
20
request.body

gives you access to the request body. So if it is XML and you want it as a NodeSeq, do:

XML.loadString(request.body)
Quaggy answered 28/3, 2012 at 17:6 Comment(1)
Make sure that Content-Type is not 'application/x-www-form-urlencoded' (see Ross' answer on groups.google.com/forum/#!topic/scalatra-user/lApjIJXiNqg)Proglottis
G
5

+1, good question

You have access to Servlet Request via "request" keyword within a Scalatra route, so getInputStream and getContentLength provide access if the post body itself is the xml string; i.e. client is not passing xml stored in named field as part of a form post. If the latter, then the below should do the trick:

post("/foo" && request.getHeader("Accept-Encoding") contains "application/xml") {
  val xml = XML.fromString(params("xml-param-field-name"))
}

If you want to use above parse from string, see Anti-XML Integration in the Scalatra Book

Gielgud answered 28/3, 2012 at 16:52 Comment(2)
am new to scala and doing this ^^ am getting compilation error on &&/contains.Cellarer
@Cellarer not sure, it's been 5 years since I used Scalatra ;-) Maybe try their Gitter channelGielgud

© 2022 - 2024 — McMap. All rights reserved.