How do you get the size of a Request in Play 2.0.x?

谁都会走 提交于 2020-01-13 03:11:45

问题


In Play Framework 2.0.3 (scala), how do you determine the size (in bytes) of any Request[_]?

We're trying to obtain this information for logging purposes.

We would expect some value from request.body.asRaw, but we always obtain None:

def logRawRequest[A](request: Request[A]) {
  request.body match {
    case c: AnyContent => println("Raw: "+c.asRaw)
  }
}

There must be something simple that we're missing, right?


Thanks for the helpful answers! It turns out that the Content-Length header is only present for POST/PUT, so we use it for those, and fallback to the length of the query for GET/DELETE, like this:

val requestSize = request.method match {
  case "POST" | "PUT" => request.headers.get(CONTENT_LENGTH).map(_.toInt).getOrElse(-1)
  case _ => request.toString().length
}

回答1:


I haven't tried this, but maybe

request.headers.get(play.api.http.HeaderNames.CONTENT_LENGTH)

would do the trick? It would work for simple POST requests at least. It would just give the body length.

GET requests don't have a body, of source -- depending on what you want to measure, request.uri.length should do it, and maybe the total size of the headers also (there could be some large cookies). If you calculate this total, you should add it to content length for POSTs.



来源:https://stackoverflow.com/questions/12585459/how-do-you-get-the-size-of-a-request-in-play-2-0-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!