问题
I want to have my Android app track its own data usage. I can get the Content-Length of the HTTP response, but I can't find how to get the size of the request before it's sent out. All the requests (GET, POST, PUT, etc) are instances of HttpUriRequest
.
Thanks
回答1:
All requests with content should be a subclass of 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.
}
回答2:
The HttpUriRequest
class inherits from the HttpRequest
class which has a method called getRequestLine()
. You can call this function and call the toString()
method and then the length()
function to find the length of the request.
Example:
HttpUriRequest req = ...;
int reqLength = req.getRequestLine().toString().length());
This will get you the length of the String
representation of the request.
来源:https://stackoverflow.com/questions/10776302/is-there-a-way-to-get-the-content-length-of-httpurirequest-before-it-gets-sent-i