java下载网络文件url

/**
 * 下载文件
 */
public static void download(HttpServletResponse response, InputStream is, String fileName, String encoding){
    if(is == null || StringUtils.isBlank(fileName)){
        return;
    }

    BufferedInputStream bis = null;
    OutputStream os = null;
    BufferedOutputStream bos = null;

    try{
        bis = new BufferedInputStream(is);
        os = response.getOutputStream();
        bos = new BufferedOutputStream(os);
        response.setContentType("application/octet-stream;charset=" + encoding);
        response.setCharacterEncoding(encoding);
        response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, encoding));
        byte[] buffer = new byte[1024];
        int len = bis.read(buffer);
        while(len != -1){
            bos.write(buffer, 0, len);
            len = bis.read(buffer);
        }

        bos.flush();
    }catch(IOException e){
        e.printStackTrace();
    }finally{
        if(bis != null){
            try{
                bis.close();
            }catch(IOException e){}
        }

        if(is != null){
            try{
                is.close();
            }catch(IOException e){}
        }
    }
}

 

 

InputStream inputStream = getInputStreamFromUrl(attachment.getPreviewUrl());
 
public static InputStream getInputStreamFromUrl(String url) throws Exception {
    if (StringUtils.isNotEmpty(url)){
        URL urlEntity = new URL(url);
        return urlEntity.openConnection().getInputStream();
    }
    return null;
}
 
public static InputStream getInputStreamUrl(String urlT) throws Exception {
    URL url = new URL(urlT);
    //打开链接
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        //设置请求方式为"GET"
        conn.setRequestMethod("GET");
        //超时响应时间为5秒
        conn.setConnectTimeout(5 * 1000);
        //通过输入流获取图片数据
        InputStream inStream = conn.getInputStream();
        return inStream;//返回Base64编码过的字节数组字符串
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception("获取流失败!");
    }
}

 

 

你可能感兴趣的:(java基础,url,java)