我正在使用 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/