我在 JSON 的帮助下从服务器获取视频 URL 。
如何将其保存在我的android项目中? (我也希望通过电子邮件发送此视频。)
答案 0 :(得分:0)
试试这个,
public String downloadImages(String serverUrl,String directory)
{
if (serverUrl == null)
return null;
String LocalFilePath=serverUrl.substring(serverUrl.lastIndexOf("/")+1, serverUrl.length());
File file = new File(directory, LocalFilePath);
if (!file.exists())
{
int bytesread = 0;
byte[] bytes = new byte[1024];
InputStream strm = null;
HttpResponse response = null;
HttpEntity entity = null;
String LocalFile = null;
FileOutputStream foStream;
BufferedOutputStream writer = null;
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
serverUrl = serverUrl.replace(" ", "%20");
HttpGet httpget = new HttpGet(serverUrl);
response = httpclient.execute(httpget);
if (response == null)
{
return null;
}
entity = response.getEntity();
strm = entity.getContent();
File dire = new File(directory);
if (!dire.isDirectory())
{
dire.mkdirs();
}
LocalFile = directory+LocalFilePath;
directory = null;
foStream = new FileOutputStream(LocalFile);
writer = new BufferedOutputStream(foStream);
do
{
bytesread = strm.read(bytes, 0, bytes.length);
if(bytesread > 0)
{
writer.write(bytes, 0, bytesread);
writer.flush();
}
} while (bytesread > 0);
writer.close();
foStream.close();
strm.close();
return LocalFile;
}
catch(Exception e)
{
file.delete();
e.printStackTrace();
return null;
}
}
else
{
return "file exist";
}
}
这将从服务器下载文件并保存在您给定的文件路径