Skip to content Skip to sidebar Skip to footer

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.

HttpUriRequestreq= ...;
longlength= -1L;
if (req instanceof HttpEntityEnclosingRequestBase) {
    HttpEntityEnclosingRequestBaseentityReq= (HttpEntityEnclosingRequestBase) req;
    HttpEntityentity= 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:

HttpUriRequestreq= ...;
intreqLength= 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?"