download java

//通过url或者图片的Blob流下载到指定目录

public String download(String urlStr,String dirPath,String fileName,byte[] imgBlob){

  if(!StringUtils.isNotEmpty(urlStr) && imgBlob == null){return null;}

  byte[] getData;

  InputStream in = null;

  try{

    if(imgBlob != null){getData = imgBlob;}

    else{ 

      urlStr = urlStr.replaceAll("\\\\","/");
      log.info("【downLoad-begin】 - url:{}",encode(urlStr,"UTF-8"));
      URL url = new URL(encode(urlStr,"UTF-8"));
      URLConnection conn = url.openConnection();
      conn.setRequestProperty("accept", "*/*");
      conn.setRequestProperty("connection", "Keep-Alive");
      conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
      conn.setRequestProperty("accept-language", "zh-CN");
      conn.addRequestProperty("Cache-Control", "no-cache");
      conn.setUseCaches(false);
      conn.setConnectTimeout(30*1000);//设置超时时间30s
      in = conn.getInputStream();
      getData = IoUtil.readBytes(in);

    }

    String suffix = getSuffix(urlStr,getData);
    String path = dirPath + fileName + "."+suffix;
    FileUtil.writeBytes(getData,path);
    return path;

  }catch(Exception e){

  log.error("获取图片失败{}",urlStr,e);
  return null;

  }finally{ 

  if (in != null) {
  try {
  in.close();
  } catch (IOException e) {
  log.error("关闭图片读取Stream失败{}",urlStr,e);
  }
  }

  }

}

posted on 2019-10-26 17:07  Lost光头  阅读(310)  评论(0编辑  收藏  举报