0

我在JSON的帮助下从服务器获取视频URL

如何将其保存在我的 android 项目中?(我也想通过电子邮件发送此视频。)

4

1 回答 1

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";
         }
    }

这将从服务器下载文件并保存在您给定的文件路径中

于 2012-09-28T12:16:09.223 回答