Is There A Way To Get The Content-Length Of HttpUriRequest Before It Gets Sent In Android / Java?
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.
Solution 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.
}
Solution 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.
Post a Comment for "Is There A Way To Get The Content-Length Of HttpUriRequest Before It Gets Sent In Android / Java?"