gpt4 book ai didi

android httpclient触发从服务器下载

转载 作者:行者123 更新时间:2023-11-29 00:36:58 25 4
gpt4 key购买 nike

我创建了一个 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文件。他们应该在流中阅读吗?谢谢

最佳答案

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com