现在的位置: 首页 > 综合 > 正文

java下载远程http地址的图片文件到本地-自动处理图片是否经过服务器gzip压缩的问题

2014年10月09日 ⁄ 综合 ⁄ 共 1017字 ⁄ 字号 评论关闭

java下载远程http地址的图片文件到本地-自动处理图片是否经过服务器gzip压缩的问题

直接上代码:

      /**
  * 下载文件到本地
  *
  * @param urlString
  *            被下载的文件地址
  * @param filename
  *            本地文件名
  * @throws Exception
  *             各种异常
  */
 public static void download(String urlString, String filename)
   throws Exception {
  // 构造URL
  URL url = new URL(urlString);
  // 打开连接
  URLConnection con = url.openConnection();
  // 输入流
  InputStream is = con.getInputStream();

  String code=con.getHeaderField("Content-Encoding");
  System.out.println("cdoe:"+code);
 
 
  if ((null!=code)&& code.equals("gzip"))
  {
   GZIPInputStream gis = new GZIPInputStream(is);
  
   // 1K的数据缓冲
   byte[] bs = new byte[1024];
   // 读取到的数据长度
   int len;
   // 输出的文件流
   OutputStream os = new FileOutputStream(filename);
   // 开始读取
   while ((len = gis.read(bs)) != -1) {
    os.write(bs, 0, len);
   }
   // 完毕,关闭所有链接
   gis.close();
   os.close();
   is.close();
  
  }
  else
  {
  
   // 1K的数据缓冲
   byte[] bs = new byte[1024];
   // 读取到的数据长度
   int len;
   // 输出的文件流
   OutputStream os = new FileOutputStream(filename);
   // 开始读取
   while ((len = is.read(bs)) != -1) {
    os.write(bs, 0, len);
   }
   // 完毕,关闭所有链接
   os.close();
   is.close();
  }

 }

抱歉!评论已关闭.