从Play框架(Scala)中的play.api.mvc.Action [AnyContent]获取响应正文 [英] Get Response body from play.api.mvc.Action[AnyContent] in Play framework (Scala)
问题描述
我有以下Play(Scala)代码:
I have the following Play (Scala) code:
object Experiment extends Controller {
//routes file directs /genki here
def genki(name: String) = Action(pipeline(name))
def pipeline(name: String) = {
req:play.api.mvc.RequestHeader => {
val template = views.html.genki(name)
Experiment.Status(200).apply(template).as("text/html")
}
}
def simple = Action {
SimpleResult(
header = ResponseHeader(200, Map(CONTENT_TYPE -> "text/plain")),
body = Enumerator("Hello World!".getBytes())
)
}
}
这可以正常编译,并且可以正常工作.
This compiles fine and works as expected.
使用scala REPL如何显示实际的html?
Using the scala REPL how can I display the actual html?
我有:
scala> val action = simple
action: play.api.mvc.Action[play.api.mvc.AnyContent] = Action(parser=BodyParser(anyContent))
我要表示的是,现在REPL中的值引用'action'是一个Action对象,类型受AnyContent约束(这是正确的说法吗?).
which I take to mean that now the value reference 'action' in the REPL is an Action object which is type-constrained for AnyContent (is that correct way to say it?).
我现在如何使用此操作来打印Http响应html内容?
how can I now use this Action to print out the Http Response html content?
非常感谢
推荐答案
基于Huw的 answer ,此处为完整的工作代码:
Building on the answer by Huw, here is the full working code:
import play.api.test._
def getStringFromAction(action:Action[AnyContent]):String = {
val request = new FakeRequest("fakeMethod", "fakeUrl", new FakeHeaders, "fakeBody")
val result = action.apply(request).run
import scala.concurrent.duration._
Helpers.contentAsString(result)(1000 millis)
}
您将需要包括以下库(在Play中默认不包含):play-test_2.11.jar
,selenium-java.jar
,selenium-api.jar
,selenium-chrome-driver.jar
,selenium-firefox-driver.jar
,selenium-remote-driver.jar
,selenium-htmlunit-driver.jar
,htmlunit-core-js.jar
和htmlunit.jar
.这些在Play或Activator发行版中可用.您还可以在build.sbt中添加依赖项,如在此处说明.
You will need to include the following libraries (not included by default in Play): play-test_2.11.jar
, selenium-java.jar
, selenium-api.jar
, selenium-chrome-driver.jar
, selenium-firefox-driver.jar
, selenium-remote-driver.jar
, selenium-htmlunit-driver.jar
, fluentlenium-core.jar
, htmlunit-core-js.jar
and htmlunit.jar
. These are available in the Play or Activator distribution. You can also add a dependency in build.sbt as explained here.
这篇关于从Play框架(Scala)中的play.api.mvc.Action [AnyContent]获取响应正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!