我想让我的Android应用跟踪自己的数据使用情况。我可以获得HTTP响应的Content-Length,但是在发出请求之前我找不到如何获取请求的大小。所有请求(GET,POST,PUT等)都是HttpUriRequest
。
由于
答案 0 :(得分: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.
}
答案 1 :(得分:0)
HttpUriRequest
类继承自HttpRequest
类,该类具有名为getRequestLine()
的方法。您可以调用此函数并调用toString()
方法,然后调用length()
函数来查找请求的长度。
示例:
HttpUriRequest req = ...;
int reqLength = req.getRequestLine().toString().length());
这将为您提供请求的String
表示的长度。