有没有办法让HttpUriRequest的内容长度让它在Android的/ Java的被发送? [英] Is there a way to get the Content-Length of HttpUriRequest before it gets sent in Android / Java?

查看:666
本文介绍了有没有办法让HttpUriRequest的内容长度让它在Android的/ Java的被发送?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有我的Andr​​oid应用程序跟踪其自己的数据使用量。我能得到的HTTP响应的内容长度,但我找不到它发送出去之前,如何获得请求的大小。所有的请求(GET,POST,PUT等)是 HttpUriRequest 实例。

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.

感谢

推荐答案

与内容的所有请求应的子类 HttpEntityEnclosingRequestBase

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.
}

这篇关于有没有办法让HttpUriRequest的内容长度让它在Android的/ Java的被发送?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆