java按http地址列表下载文件队列

来源:互联网 发布:欧洲旅游团 知乎 编辑:程序博客网 时间:2024/06/05 14:32

本文实现的功能是通过url列表下载文件队列,http url地址如:http://172.16.53.187:8080/LiveDownServer/Media/DownloadFile?path=E%3A%2Fvideofiles%2Ftest123%2Fdevelop%2F2015%2F06%2F12%2Fts%2F12%2F20150612124328.ts 路径经过了编码,可以利用java自带函数java.net.URLDecoder.decode进行解码,解码之后添加到url列表利用HttpURLConnection循环下载,此功能不足之处是无法修改下载文件的路径,后续会增加修改下载文件路径功能。

//http文件队列下载
 public void httplistDownload() throws IOException{  
  String path=ServletActionContext.getRequest().getParameter("path"); 
  //返回ts切片地址列表
  URL stSpaceUrl = new URL(path);
        HttpURLConnection storageconn = (HttpURLConnection) stSpaceUrl.openConnection();
        storageconn.connect();
        BufferedReader storageReader = new BufferedReader(new InputStreamReader(storageconn.getInputStream()));
        String httpresponse=storageReader.readLine();
  
  httpresponse=httpresponse.substring(1,httpresponse.lastIndexOf("]"));  
  String[] urlarray=httpresponse.split(", ");
       
  int BUFFER_SIZE= 10240; //缓冲区大小10Kb
  String strurl=null;
  String filename=null;
  String filepath=null;
  Vector<String> vdownload=new Vector<String>(); //url列表
  Vector<String> vfilename=new Vector<String>(); //文件名列表
  
  for(int i=0;i<urlarray.length;i++){
   filepath=java.net.URLDecoder.decode(urlarray[i], "utf-8");
   filename=filepath.substring(filepath.lastIndexOf("/")+1);
   vdownload.add(filepath); //解码之后,添加到url列表
   vfilename.add(filename); //文件名添加到列表
  }
  
  //按列表顺序保存资源
  for(int i=0;i<vdownload.size();i++)
  {
   strurl=(String)vdownload.get(i); //从列表中取出url
   filename=(String)vfilename.get(i); //从列表中取出文件名
   FileOutputStream fos=null;
   BufferedInputStream bis=null;
   HttpURLConnection httpUrl=null;
   URL url=null;
   byte[] buffer=new byte[BUFFER_SIZE];
   int size=0;
   //建立连接
   url=new URL(strurl);
   httpUrl=(HttpURLConnection)url.openConnection();
   //连接指定的资源
   httpUrl.connect();
   //获取网络输入流
   bis=new BufferedInputStream(httpUrl.getInputStream());
   //建立文件
   fos=new FileOutputStream("E:\\download\\"+filename);
   //保存文件
   while((size=bis.read(buffer))!=-1)
   {
    fos.write(buffer,0,size);
   }
   fos.close();
   bis.close();
   httpUrl.disconnect();
  }

 }

1 0