Android HttpClient:传输了多少数据?

时间:2013-11-08 17:02:56

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

1 个答案:

答案 0 :(得分: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();
    }