【问题标题】:Android HttpClient: How much data is transferred?Android HttpClient:传输了多少数据?
【发布时间】:2013-11-08 17:02:56
【问题描述】:

我正在使用 PHP 脚本来访问我的数据库中的数据。

但是,如果您的计划不包括 3G 访问,数据传输可能会很昂贵。因此,如果周围没有 Wifi,最好知道我的应用程序实际下载/上传/使用了多少。

有没有一种方法可以确定我要上传多少字节(后参数)然后下载(字符串输出/php 脚本的响应)?

使用代码:

//http post
try {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(new UrlEncodedFormEntity(arguments));
    HttpResponse httpresponse = httpclient.execute(httppost); 
    HttpEntity entity = httpresponse.getEntity();
    is = entity.getContent();
    Log.e("log_tag", "connection success ");
} catch(Exception e) {
    Log.e("log_tag", "Error in http connection "+e.toString());
}

【问题讨论】:

    标签: java android androidhttpclient


    【解决方案1】:

    使用getEntity().getContentLength() 获取HTTP 请求和响应中的HTTP 消息大小。并将consumed 属性保存在SharedPreferences 中,以便在另一个会话中恢复它。

    代码如下:

    static long consumed = 0;
    
        //http post
        long consumedNow = 0;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(arguments));
            consumedNow += httppost.getEntity().getContentLength();
            HttpResponse httpresponse = httpclient.execute(httppost);
            HttpEntity entity = httpresponse.getEntity();
            is = entity.getContent();
            consumedNow += httpresponse.getEntity().getContentLength(); 
            Log.e("log_tag", "connection success ");
        } catch(Exception e) {
            Log.e("log_tag", "Error in http connection "+e.toString());
        } finally {
            consumed += consumedNow;
            SharedPreferences sp = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putLong("consumed", value);
            editor.commit();
        }
    

    【讨论】:

    • 嗯。我没有使用 HttpURLConnection。我发布了我在上面使用的代码。有什么想法吗?
    • 非常感谢。到底消耗到底是什么?字节数还是什么?
    • 是的,字节。使用:stackoverflow.com/questions/3758606/… 转换为可读格式,您可以将使用的数据保存在 SharedPreferences 中(以在不同的用户会话中恢复)。
    • 好的。但这怎么可能呢?我得到一个长度为 688 个字符的字符串作为响应。而这只有 2 个字节?这可能吗?
    • 我不习惯 HttpClient 也没有测试代码,但可能你的 http 服务器没有发送填充的 Content-Length。所以,在读取内容后尝试调用getContentLength或者获取内容并在读取时增加consumedNow变量。
    猜你喜欢
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多