android httpclient触发从服务器下载

标签 android download get httpclient

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

10.0.2.2:端口号/路径/到/文件

服务器启动文件下载过程。客户当然不会这么做,用来测试文件服务器就可以了。 我是 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文件感到困惑。应该在流中读取它们吗?谢谢

最佳答案

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

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

关于android httpclient触发从服务器下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12078440/

相关文章:

java - 下载加速

Android DownloadManager 在完成下载时处理通知单击事件

android - 如何处理读者收到的S-block?

java - 监听我自己的应用程序制作的 LogCat Entires

Android 查找当前位置错误

node.js - 通过请求在 Node.js 中获取下载进度

json - 使用 RestTemplate 进行部分 JSON 检索

javascript - 如何在多个Jquery Get函数中等待

javascript - 添加附加参数以获取/发布 ajax

android - 将下载的图像保存在 Android 的图库中