博客
关于我
java后台通过http请求下载文件
阅读量:793 次
发布时间:2023-01-28

本文共 1844 字,大约阅读时间需要 6 分钟。

 java后台通过http请求下载文件,直接反馈给前端

public void downLoad(HttpServletResponse response,String HTTP_URL, String filename) {	        BufferedInputStream bis = null;	        BufferedOutputStream bos = null;	        try {	            URL url = new URL(HTTP_URL);	            HttpURLConnection connection = (HttpURLConnection)url.openConnection();	            connection.setRequestMethod("GET");	            connection.setConnectTimeout(5000);	            connection.setReadTimeout(6000);	            connection.connect();	            int responseCode = connection.getResponseCode();	            System.out.println("responseCode=" + responseCode);	            if (responseCode == 200) {	                InputStream is = connection.getInputStream();	                bis = new BufferedInputStream(is);	                response.reset();	                response.setContentType("application/x-msdownload");	                response.setHeader("Content-Disposition", "attachment;filename=".concat(new String(filename.getBytes("GBK"), "ISO-8859-1")));	                OutputStream fos = response.getOutputStream();	                bos = new BufferedOutputStream(fos);	                boolean b = false;	                byte[] byArr = new byte[1024];	                int b1;	                while((b1 = bis.read(byArr)) != -1) {	                    bos.write(byArr, 0, b1);	                }	                bos.flush();	            }	            connection.disconnect();	        } catch (Exception var21) {	            var21.printStackTrace();	        } finally {	            try {	                if (bis != null) {	                    bis.close();	                }	                if (bos != null) {	                    bos.close();	                }	            } catch (IOException var20) {	                var20.printStackTrace();	            }	        }	    }

 

转载地址:http://tsryk.baihongyu.com/

你可能感兴趣的文章
Python爬虫训练:爬取酷燃网视频数据
查看>>
解决微信小程序项目导入的问题:app.json 未找到、 __wxConfig is not defined
查看>>
非迅捷|PDF、Word、PPT、Excel、图片等互相在线转换:免费、简单、快速、零错误、无套路
查看>>
laravel server error 服务器内部错误
查看>>
一道简单的访问越界、栈溢出pwn解题记录
查看>>
响应的HTTP协议格式+常见的响应码
查看>>
springboot redis key乱码
查看>>
解决打开 json 文件中文乱码的问题
查看>>
计算机网络基础:PKI(公钥基础设施)
查看>>
乒乓球问题
查看>>
Trae国内版发布,中国首款AI 原生IDE 正式上线,配置Doubao-1.5-pro,支持切换满血版DeepSeek 模型
查看>>
回溯法介绍
查看>>
2025最新智能优化算法:改进型雪雁算法(Improved Snow Geese Algorithm, ISGA)求解23个经典函数测试集
查看>>
有了Trae,人人都是程序员的时代来了
查看>>
程序员都看不懂的代码
查看>>
LLM+多智能体协作:基于CrewAI与DeepSeek的邮件自动化实践
查看>>
404页面自动跳转源码
查看>>
46:把数字翻译成字符串(动态规划)
查看>>
500套精美Logo样机模板可直接套用、轻松制作炫酷logo
查看>>
ASP.NET MVC4 json序列化器
查看>>