如何创建一个在Play中打印整个请求和响应的方法?

时间:2018-04-07 09:42:53

标签: playframework-2.6

我想创建一个可以从Request调用的辅助方法,并打印Request的不同参数。我尝试做类似下面的事情,但我需要将类型参数传递给import play.api.mvc.Request package object utilities { def printPlayHttpRequest (request:Request): Unit ={ //Request needs type parameter. What should I pass as type parameter? } } 。我应该为类型参数传递什么?

apply

查看Request对象的def apply[A](rh: RequestHeader, body: A): Request[A] 方法,似乎传递的type参数对应于Body类型。那么我需要传递一些体型吗?

<?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapFragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>

1 个答案:

答案 0 :(得分:0)

从Play文档中,我认为A中的Request[A]对应于正文的类型,它可以是任何Scala类型作为请求正文,例如String,NodeSeq,Array [Byte],JsonValue或者java.io.File,只要我们有一个能够处理它的主体解析器

来自文档

Previously we said that an Action was a Request => Result function. This is not entirely true. Let’s have a more precise look at the Action trait:

trait Action[A] extends (Request[A] => Result) {
  def parser: BodyParser[A]
}

First we see that there is a generic type A, and then that an action must define a BodyParser[A]. With Request[A] being defined as:

trait Request[+A] extends RequestHeader {
  def body: A
}

The A type is the type of the request body. We can use any Scala type as the request body, for example String, NodeSeq, Array[Byte], JsonValue, or java.io.File, as long as we have a body parser able to process it.

To summarize, an Action[A] uses a BodyParser[A] to retrieve a value of type A from the HTTP request, and to build a Request[A] object that is passed to the action code.

以下是我的实施

import play.api.mvc.{AnyContent, Request}

package object utilities {

  def printPlayHttpRequest (request:Request[AnyContent]): Unit ={
    println(s"Attr: ${request.attrs}, \n Body: ${request.body},  \n connection: ${request.connection},  \n headers: ${request.headers},  \n method: ${request.method}, \n target:  ${request.target},  \n version: ${request.version},  \n mediatype: ${request.mediaType}")
  }
}