如何通过url从服务器下载音频文件并将其保存到SD卡。
我正在使用以下代码:
public void uploadPithyFromServer(String imageURL, String fileName) {
try {
URL url = new URL(GlobalConfig.AppUrl + imageURL);
File file = new File(fileName);
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 1024 * 50);
FileOutputStream fos = new FileOutputStream("/sdcard/" + file);
byte[] buffer = new byte[1024 * 50];
int current = 0;
while ((current = bis.read(buffer)) != -1) {
fos.write(buffer, 0, current);
}
fos.flush();
fos.close();
bis.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
上面的代码没有下载音频文件。 如果在清单文件中使用任何权限,请告诉我..(我已经使用过互联网许可) 请帮忙
感谢..
答案 0 :(得分:2)
你还必须添加
如果您希望将数据写入SD卡,请android.permission.WRITE_EXTERNAL_STORAGE
。
如果你有任何IOExceptions,也会发布你的logcat输出。
答案 1 :(得分:2)
您的示例未指定请求方法和一些mimetypes和东西 在这里您可以找到mimetypes http://www.webmaster-toolkit.com/mime-types.shtml的列表 找到与您相关的mimetypes,并将其添加到代码中指定的mimetypes中。
哦,顺便说一下,下面是普通的Java代码。您必须替换在SD卡上存储文件的位。目前没有模拟器或手机来测试该部件 另请参阅此处的sd存储权限文档:http://developer.android.com/reference/android/Manifest.permission_group.html#STORAGE
public static void downloadFile(String hostUrl, String filename)
{
try {
File file = new File(filename);
URL server = new URL(hostUrl + file.getName());
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.addRequestProperty("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-shockwave-flash, */*");
connection.addRequestProperty("Accept-Language", "en-us,zh-cn;q=0.5");
connection.addRequestProperty("Accept-Encoding", "gzip, deflate");
connection.connect();
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream("c:/temp/" + file.getName());
byte[] buffer = new byte[1024];
int byteReaded = is.read(buffer);
while(byteReaded != -1)
{
os.write(buffer,0,byteReaded);
byteReaded = is.read(buffer);
}
os.close();
} catch (IOException e) {
e.printStackTrace();
}
然后打电话,
downloadFile("http://localhost/images/bullets/", "bullet_green.gif" );
编辑: 坏编码我。 将输入InputStream包装在BufferedInputStream中。无需指定缓冲区等 默认值很好。