Is there a way to get the Content-Length of HttpUriRequest before it gets sent in Android / Java?

我只是一个虾纸丫 提交于 2020-01-06 03:35:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!