我想下载一些保存在我的在线服务器上的联系人,然后在我的 Activity 中显示它们。我已经编写了一项服务,并且我正在提供来自 onStartCommand
函数的代码 fragment ,其中正在完成此下载。
public int onStartCommand(Intent intent, int flags, int startId)
{
String responseStr = "";
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "get_contact"));
nameValuePairs.add(new BasicNameValuePair("uId", uId + ""));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader (new InputStreamReader(httpResponse.getEntity().getContent()));
responseStr = in.readLine();
in.close();
}
catch (ClientProtocolException e)
{
Log.e("EXCEPTION", "ClientProtocolException");
}
catch (IOException e)
{
Log.e("EXCEPTION", "IOException");
}
this.stopSelf();
return Service.START_STICKY;
}
但是这段代码的问题是下载数据花费的时间太长了。请建议我以任何方式快速下载并在我的 Activity 中显示此数据。
预先感谢您的帮助。
最佳答案
嗯,如果您的服务器或连接速度很慢,您的客户端代码就无能为力了。
但是,您绝对应该考虑压缩来自 Web 服务器的响应,并在客户端代码上添加 header :
接受编码:gzip
关于android - 在 android 2.1 中从服务器下载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9548751/