欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java使用http实现文件下载学习示例

程序员文章站 2024-02-27 21:55:21
复制代码 代码如下:package com.hongyuan.test; import java.io.file;import java.io.fileoutputstr...

复制代码 代码如下:

package com.hongyuan.test;

import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.net.httpurlconnection;
import java.net.malformedurlexception;
import java.net.url;
import java.net.urldecoder;

public class filedownload {

 public static final string local_path="d:/";

 public static void main(string[] args) {
  //待下载文件地址
  string fileurl="http://211.162.55.16/cdn.baidupcs.com/file/6a73dab7c03023a9835cc737f447674d?xcode=af6ffdc43a44169bac968d32c4bd420084a9a97c308112c9&fid=3255571826-250528-130564002&time=1397293108&sign=fdtaxer-dcb740ccc5511e5e8fedcff06b081203-mqkoerdtxpyqwwyjki%2bxkjpxn5k%3d&to=cb&fm=n,b,u,nc&newver=1&expires=1397297563&rt=sh&r=854979042&logid=1751715936&sh=1&vuk=3255571826&fn=web%e7%a8%8b%e5%ba%8f%e8%ae%be%e8%ae%a1%20%e7%ac%ac5%e7%89%88.pdf&wshc_tag=0&wsiphost=ipdbm";
  inputstream in=null;
  outputstream out=null;
  httpurlconnection conn=null;
  string filename=null;
  try {
   //初始化连接
   url url=new url(fileurl);
   conn = (httpurlconnection) url.openconnection();
   conn.setdoinput(true);
   conn.setdooutput(true);

   //获取文件名
   string disposition=conn.getheaderfield("content-disposition");
   if(disposition!=null&&!"".equals(disposition)){
    //从头中获取文件名
    filename=disposition.split(";")[1].split("=")[1].replaceall("\"","");
   }else{
    //从地址中获取文件名
    filename=fileurl.substring(fileurl.lastindexof("/")+1);
   }

   if(filename!=null&&!"".equals(filename)){
    //文件名解码
    filename=urldecoder.decode(filename, "utf-8");
   }else{
    //如果无法获取文件名,则随机生成一个
    filename="file_"+(int)(math.random()*10);
   }

   //读取数据
   if(conn.getresponsecode()==httpurlconnection.http_ok){
    byte[] buffer=new byte[2048];
    in = conn.getinputstream();
    out=new fileoutputstream(new file(local_path,filename));
    int count=0;
    int finished=0;
    int size=conn.getcontentlength();
    while((count=in.read(buffer))!=-1){
     if(count!=0){
      out.write(buffer,0,count);
      finished+=count;
      system.out.printf("########################################---->%1$.2f%%\n",(double)finished/size*100);
     }else{
      break;
     }
    }
   }
  } catch (malformedurlexception e) {
   e.printstacktrace();
  } catch (ioexception e) {
   e.printstacktrace();
  }finally{
   try {
    out.close();
    in.close();
    conn.disconnect();
   } catch (ioexception e) {
    e.printstacktrace();
   }
  }
 }
}