我创建了一个 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/