1

我想让我的 Android 应用程序跟踪它自己的数据使用情况。我可以获取 HTTP 响应的 Content-Length,但在发送请求之前我找不到如何获取请求的大小。所有请求(GET、POST、PUT 等)都是HttpUriRequest.

谢谢

4

2 回答 2

3

所有带有内容的请求都应该是HttpEntityEnclosingRequestBase.

HttpUriRequest req = ...;
long length = -1L;
if (req instanceof HttpEntityEnclosingRequestBase) {
    HttpEntityEnclosingRequestBase entityReq = (HttpEntityEnclosingRequestBase) req;
    HttpEntity entity = entityReq.getEntity();
    if (entity != null) {
        // If the length is known (i.e. this is not a streaming/chunked entity)
        // this method will return a non-negative value.
        length = entity.getContentLength();
    }
}

if (length > -1L) {
    // This is the Content-Length. Some cases (streaming/chunked) doesn't
    // know the length until the request has been sent however.
}
于 2012-05-27T19:15:31.177 回答
0

该类HttpUriRequest继承自HttpRequest具有名为 的方法的类getRequestLine()。您可以调用此函数并调用该toString()方法,然后调用该length()函数来查找请求的长度。

例子:

HttpUriRequest req = ...;
int reqLength = req.getRequestLine().toString().length());

String这将为您提供请求表示的长度。

于 2012-05-27T19:38:16.783 回答