Marco7757
Marco7757

Reputation: 764

Android HttpClient: How much data is transferred?

I'm using a PHP script to access data in my database.

However, data transfer might be expensive if your plan doesn't cover 3G access. So if there's no Wifi around, it would be good to know, how much my application is actually downloading/uploading/using.

Is there a way I can determine how much Bytes I'm uploading (post arguments) and then downloading (string output/response of the php script)?

Code in use:

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

Upvotes: 0

Views: 439

Answers (1)

Italo Borssatto
Italo Borssatto

Reputation: 15689

Use getEntity().getContentLength() to get the HTTP message size, in HTTP request and response. And save the consumed property in SharedPreferences to recover it in another session.

The code will look like:

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

Upvotes: 1

Related Questions