在Play 2.0.x中,如何获取请求的大小? [英] How do you get the size of a Request in Play 2.0.x?

查看:71
本文介绍了在Play 2.0.x中,如何获取请求的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Play Framework 2.0.3(标量)中,您如何确定任何请求的大小(以字节为单位)[_]?

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.

我们希望从request.body.asRaw获得一些值,但是我们总是获得None:

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?

感谢有用的答案!事实证明,Content-Length标头仅在POST/PUT中存在,因此我们将其用于那些,并回退到GET/DELETE的查询长度,如下所示:

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
}

推荐答案

我还没有尝试过,但是也许

I haven't tried this, but maybe

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

能做到这一点吗?它至少适用于简单的POST请求.它只会给出身体的长度.

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

GET请求没有源正文-根据您要度量的内容,request.uri.length应该这样做,并且标题的总大小也可能(可能有一些大的cookie).如果您计算此总数,则应将其添加到POST的内容长度中.

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.

这篇关于在Play 2.0.x中,如何获取请求的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆