android httpclient触发从服务器下载

时间:2012-08-22 17:32:46

标签: android download get httpclient

我创建了一个HTTP文件服务器,目的是将媒体文件(mp3,ogg等)传输到Android设备。从Android浏览器访问服务器时

10.0.2.2:portNumber/path/to/file

服务器启动文件下载过程。当然客户不会做这样的事情,它可以用来测试文件服务器。 我是Android开发新手,并了解到httpclient包可以管理get / post请求。以下是我用于阅读回复的示例代码

DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
  HttpResponse execute = client.execute(httpGet);
  InputStream content = execute.getEntity().getContent();

  BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
  String s = "";
  while ((s = buffer.readLine()) != null) {
    response += s;
  }
} catch (Exception e) {
  e.printStackTrace();
}

return response;

当服务器以JSON格式发送文件列表时,上述代码可以正常工作。由于发送文件的服务器部分已被编码,我所困的点是在android上检索媒体文件。

我对如何接收服务器发送的mp3文件感到困惑。它们应该在流中读取吗?感谢

1 个答案:

答案 0 :(得分:2)

是的,您希望通过输入流将文件读取到磁盘上。 这是一个例子。如果您不想要文件下载进度条,则删除与进度相关的代码。

try {
        File f = new File("yourfilename.mp3");
        if (f.exists()) {
            publishProgress(100,100);
        } else {
            int count;
            URL url = new URL("http://site:port/your/mp3file/here.mp3");
            URLConnection connection = url.openConnection();
            connection.connect();
            int lengthOfFile = connection.getContentLength();
            long total = 0;
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(f);
            byte data[] = new byte[1024];
            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress((int)(total/1024),lengthOfFile/1024);
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();
        }
    } catch (Exception e) {
        Log.e("Download Error: ", e.toString());
    }