简体   繁体   中英

PlayFramework: Get original request xml body as string

I'm receiving a request with an xml as body, the problem is that I've to read the original string that's inside the body. This because there are some comments in the xml header that I've to read to detect the type of document.

As per play framework documentation you've to tell play framework to parse the request body as xml

def sayHello = Action { request =>
  request.body.asXml.map { xml =>
    (xml \\ "name" headOption).map(_.text).map { name =>
      Ok("Hello " + name)
    }.getOrElse {
      BadRequest("Missing parameter [name]")
    }
  }.getOrElse {
    BadRequest("Expecting Xml data")
  }
}

that works fine, however, if I try to print xml.toString I don't get the original xml with the comments as they're outside the main xml element.

I've also tried to use request.body.asText but it checks the Content-Type header and since it's application/xml it doesn't return the string but instead it returns None

How can I extract the original body of the request as string?

You can use tolerantText like

def save = Action(parse.tolerantText) { request =>
  Ok("Got: " + request.body)
}

This one doesn't check the Content-Type header and always loads the request body as a String.

https://www.playframework.com/documentation/2.4.x/ScalaBodyParsers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM