java - Android HttpClient : How much data is transferred?

标签 java android androidhttpclient

我正在使用 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());
}

最佳答案

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

代码如下所示:

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();
    }

关于java - Android HttpClient : How much data is transferred?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19864605/

相关文章:

android - react native 音频播放器

android - 自定义键盘 android 中显示褪色的文本

android - javax.net.ssl.SSLPeerUnverifiedException : No peer certificate on HttpClient but works fine with HttpUrlConnection

Android 6.0 Marshmallow (API 23) 中弃用了 AndroidHttpClient 和 HttpGet API

android - 无法解析符号 HttpEntity、HttpResponse

Java - 从与本地不同的时区转换为 UTC

java - RabbitMQ channel 最佳实践

Java http post相关问题

java.sql.Date 到 joda 时间转换

java - Android:在 ListView 中将整数读取为字符串